diff --git a/README.md b/README.md index 179d885..9c6d267 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ account checks run, and Ethereum publication remains the oracle's responsibility | Option | Default | Meaning | | ------------------------ | ------- | ----------------------------------------------------- | | `--webhook-timeout` | 10 | Overall request timeout, seconds. | -| `--webhook-interval` | 1 | Minimum seconds between request starts. | +| `--webhook-interval` | 0.005 | Minimum seconds between request starts. | | `--webhook-backoff-base` | 1 | First retry's lower bound; upper bound is twice this. | | `--webhook-backoff-cap` | 150 | Maximum lower bound; upper bound is twice this. | @@ -82,7 +82,7 @@ merely to clear a warning. See the [operator guide](docs/operations.md#configura | Component | Modules and responsibility | | --- | --- | | `runtime` | `cli`, `config`, `serving`: arguments, validated configuration, KERIpy stores and HIO task/resource ownership. | -| `receiving` | `directing`, `grants`: finite CESR HTTP intake, shared parser/escrows, IPEX replay and duplicate-safe work creation. | +| `receiving` | `directing`, `grants`, `keying`: finite CESR HTTP intake, shared parser/escrows, indexed accepted key-state reads, IPEX replay and duplicate-safe work creation. | | `verification` | `coordinating`, `credentials`, `eoa`, `worker`, `rpc`: initial credential/wallet/account verification; `constants`, `schema_cache`, `errors` support that contract. | | `associations` | `accepting`, `revoking`, `statusing`: application acceptance, verified association revocation and public stored status. | | `delivery` | `authing`, `delivering`: HTTP signatures, webhook attempts, retry pacing and response policy. | diff --git a/docs/operations.md b/docs/operations.md index a545371..07219ca 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -111,6 +111,25 @@ when the association had an original outbox obligation. Local-only acceptance becomes revoked locally without an event. Revoking an old association does not revoke its replacement. +## Queue latency and key-state reads + +The root HIO scheduler offers workers a turn every five milliseconds. Each worker +still advances one operation at a time through its dedicated durable phases; this +cadence is not a request deadline or a promise of parallel verification. Synchronous +validation, native KERI processing and durable LMDB commits can take longer than +one turn. Large bursts accumulate queue wait even when HTTP intake returns quickly. + +Accepted KERI key state supplies the establishment event and witness set for +accepted events in the current establishment epoch. Older anchors continue to use +their historical authority, including after keys or witnesses rotate. The reader +does not cache an association's acceptance or revocation verdict. Validation before +and after RPC and the permanent nonce claim remain in place. + +Ordinary webhook requests default to a five-millisecond minimum start interval. +Use `--webhook-interval` to pace a slower receiver. This interval is independent of +failure backoff, `Retry-After`, and the three-attempt budget. No additional worker +concurrency, batching, locks or weaker LMDB durability are introduced. + ## Verification and intake failures The service progresses one item per worker through dedicated durable phases: diff --git a/src/eoa_verifier/delivery/__init__.py b/src/eoa_verifier/delivery/__init__.py index 766327a..fdf18c9 100644 --- a/src/eoa_verifier/delivery/__init__.py +++ b/src/eoa_verifier/delivery/__init__.py @@ -3,3 +3,6 @@ Signature mechanics, HTTP client lifetime and application progression have separate owners. The sender reads dedicated durable phases, never history scans. """ + +# Minimum seconds between ordinary webhook starts; failure backoff is independent. +DEFAULT_INTERVAL = 0.005 diff --git a/src/eoa_verifier/delivery/delivering.py b/src/eoa_verifier/delivery/delivering.py index 942d65c..d64a222 100644 --- a/src/eoa_verifier/delivery/delivering.py +++ b/src/eoa_verifier/delivery/delivering.py @@ -11,6 +11,7 @@ from eoa_verifier.persistence.records import DeliveryReference +from . import DEFAULT_INTERVAL from .authing import AuthenticationError from .httping import WebhookHttp @@ -34,7 +35,7 @@ def __init__( transport=None, *, association_reader, - interval=1.0, + interval=DEFAULT_INTERVAL, backoff_base=1.0, backoff_cap=150.0, clock=time.time, @@ -231,7 +232,7 @@ def __init__( keys, association_reader, timeout=10.0, - interval=1.0, + interval=DEFAULT_INTERVAL, backoff_base=1.0, backoff_cap=150.0, clock=time.time, diff --git a/src/eoa_verifier/receiving/keying.py b/src/eoa_verifier/receiving/keying.py new file mode 100644 index 0000000..663507e --- /dev/null +++ b/src/eoa_verifier/receiving/keying.py @@ -0,0 +1,69 @@ +"""Read accepted KERI key state without repeatedly traversing current epochs. + +KERIpy owns validation and the accepted state index. Its latest establishment +governs accepted interactions at or after that establishment. Earlier anchors +still use KERIpy's historical traversal. This reader adds no persistent cache, +invalidation policy, or alternate signature-validation rules. +""" + +from keri.core import eventing, serdering +from keri.db import dbing + + +def _current_est(kvy, pre, sn): + """Return the indexed establishment governing accepted ``pre``/``sn``, if any. + + kvy borrows KERIpy's accepted Kevers and database. Both sequence bounds and + the exact accepted KEL entry are required: a current key-state record alone + does not establish acceptance of a future or missing event. + """ + try: + kever = kvy.kevers[pre] + except KeyError: + return None + lastEst = kever.lastEst + if not lastEst.s <= sn <= kever.sn: + return None + eventDig = kvy.db.getKeLast(dbing.snKey(pre, sn)) + if eventDig is None: + return None + if kvy.db.getEvt(dbing.dgKey(pre, bytes(eventDig))) is None: + return None + estRaw = kvy.db.getEvt(dbing.dgKey(pre, lastEst.d)) + return serdering.SerderKERI(raw=bytes(estRaw)) if estRaw is not None else None + + +def est_event(kvy, pre, sn): + """Return the establishment authoritative for one accepted issuer event. + + Use the accepted index within the current epoch; preserve KERIpy's historical + lookup and missing-event behavior for every other sequence number. The + explicit base-class call also lets the parser below share this reader. + kvy is a borrowed Kevery, pre is the issuer's qb64 AID string, and sn is an + integer KEL sequence number. Return a SerderKERI or None when unavailable. + """ + est = _current_est(kvy, pre, sn) + return est if est is not None else eventing.Kevery.fetchEstEvent(kvy, pre, sn) + + +class Kevery(eventing.Kevery): + """Keep native KERI validation with indexed reads inside the current epoch. + + Constructor, acceptance, escrow and signature behavior belong to KERIpy. + Only its public establishment/witness lookup methods are specialized. + """ + + def fetchEstEvent(self, pre, sn): + """Return the accepted event's authoritative establishment Serder or None.""" + return est_event(self, pre, sn) + + def fetchWitnessState(self, pre, sn): + """Return historical witness Prefixers, using the accepted index where authoritative. + + Preserve the native traversal outside an accepted current-epoch event, + including its behavior for future sequence numbers and missing entries. + """ + est = _current_est(self, pre, sn) + if est is not None: + return self.db.wits.get(dbing.dgKey(pre, est.said)) + return super().fetchWitnessState(pre, sn) diff --git a/src/eoa_verifier/runtime/config.py b/src/eoa_verifier/runtime/config.py index 1e1e7a2..82a72bc 100644 --- a/src/eoa_verifier/runtime/config.py +++ b/src/eoa_verifier/runtime/config.py @@ -7,6 +7,8 @@ from hio.core.http import httping as hio_httping from keri.core import coring +from ..delivery import DEFAULT_INTERVAL + @dataclass(frozen=True) class ServiceConfig: @@ -50,7 +52,7 @@ class ServiceConfig: # 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_interval: float = DEFAULT_INTERVAL webhook_backoff_base: float = 1.0 webhook_backoff_cap: float = 150.0 diff --git a/src/eoa_verifier/runtime/serving.py b/src/eoa_verifier/runtime/serving.py index fff8af8..89b9a45 100644 --- a/src/eoa_verifier/runtime/serving.py +++ b/src/eoa_verifier/runtime/serving.py @@ -14,7 +14,7 @@ notifying, oobiing, ) -from keri.core import eventing, parsing, routing +from keri.core import parsing, routing from keri.db import basing, dbing from keri.end import ending from keri.help import helping @@ -39,6 +39,7 @@ from ..persistence.registry import VerifierReger from ..receiving.directing import CesrEnd, Receiver from ..receiving.grants import GrantNotificationDoer, IpexGrantAdapter +from ..receiving.keying import Kevery from ..receiving.replaying import GrantReplayService from ..verification.constants import ASSOCIATION_SCHEMA from ..verification.coordinating import VerificationCoordinator @@ -51,6 +52,9 @@ logger = logging.getLogger(__name__) +# Seconds per root scheduler turn; each worker still advances only one operation. +SERVICE_TOCK = 0.005 + class VerifierService(doing.DoDoer): """Own service tasks and sockets while borrowing the caller's open stores.""" @@ -75,7 +79,7 @@ def __init__(self, config, *, hby, rgy, baser, noter, **kwa): cues = decking.Deck() router = routing.Router() rvy = routing.Revery(db=hby.db, rtr=router, lax=True, local=False) - kvy = eventing.Kevery( + kvy = Kevery( db=hby.db, cues=cues, rvy=rvy, lax=True, local=False, direct=False ) kvy.registerReplyRoutes(router) @@ -283,4 +287,4 @@ def run_service(config: ServiceConfig, *, expire: float = 0.0): f"eoa-verifier serving {service.hab.pre} on {config.host}:{config.http_port}", flush=True, ) - doing.Doist(limit=expire, tock=0.03125, real=True).do(doers=[service]) + doing.Doist(limit=expire, tock=SERVICE_TOCK, real=True).do(doers=[service]) diff --git a/src/eoa_verifier/verification/evidence.py b/src/eoa_verifier/verification/evidence.py index bc5077d..777b689 100644 --- a/src/eoa_verifier/verification/evidence.py +++ b/src/eoa_verifier/verification/evidence.py @@ -5,6 +5,7 @@ from keri.db import dbing from keri.peer import exchanging +from eoa_verifier.receiving.keying import est_event from eoa_verifier.verification.errors import ( MissingCredentialArtifactsError, VerificationError, @@ -134,14 +135,15 @@ def verify_witnessed_anchor(self, association): raise MissingCredentialArtifactsError( "association issuance anchor is unavailable" ) - est = self._rgy.hby.kvy.fetchEstEvent(pre=association.issuer, sn=seqner.sn) + est = est_event(self._rgy.hby.kvy, association.issuer, seqner.sn) if est is None: raise MissingCredentialArtifactsError( "issuer establishment event is unavailable" ) if not est.bn: raise VerificationError("association issuer has no witnessed KEL") - wits = self._rgy.hby.kvy.fetchWitnessState(association.issuer, seqner.sn) + # Start at the establishment already found; avoid walking the KEL twice. + wits = self._rgy.hby.kvy.fetchWitnessState(association.issuer, est.sn) anchor = self._rgy.hby.db.getEvt(dbing.dgKey(association.issuer, saider.qb64)) wigs = self._rgy.hby.db.getWigs(dbing.dgKey(association.issuer, saider.qb64)) _, indices = eventing.verifySigs( diff --git a/tests/delivery/test_delivering.py b/tests/delivery/test_delivering.py index 14a7c9f..881ec48 100644 --- a/tests/delivery/test_delivering.py +++ b/tests/delivery/test_delivering.py @@ -57,6 +57,7 @@ def lower_bound(lower, upper): writer=DeliveryWriter(outbox), keys=ServiceKeys(None), clock=clock, + interval=1.0, uniform=lower_bound, max_attempts=12, association_reader=AssociationReader(outbox), @@ -94,6 +95,7 @@ def test_cooldown_survives_restart_and_gates_new_events(outbox): writer=DeliveryWriter(outbox), keys=ServiceKeys(None), clock=clock, + interval=1.0, uniform=lambda low, high: high, association_reader=AssociationReader(outbox), ) @@ -118,6 +120,7 @@ def unavailable(delivery): writer=DeliveryWriter(outbox), keys=ServiceKeys(None), clock=clock, + interval=1.0, association_reader=AssociationReader(outbox), ) starts = [] diff --git a/tests/receiving/test_keying.py b/tests/receiving/test_keying.py new file mode 100644 index 0000000..d41a90b --- /dev/null +++ b/tests/receiving/test_keying.py @@ -0,0 +1,124 @@ +"""Native KEL lookup contracts across interactions, rotations and absent events. + +These tests exercise actual KERIpy stores and key-state changes. Signature and +TEL validation remain covered by the witnessed IPEX integration flow; this +module checks which historical establishment and witness set they receive. +""" + +from unittest.mock import patch + +import pytest +from keri import core +from keri.app import habbing +from keri.core import eventing +from keri.db import dbing + +from eoa_verifier.receiving.keying import Kevery, est_event + + +@pytest.fixture +def issuer(): + """Borrow a native issuer with one witness and accepted local KEL entries. + + The witness prefix identifies its key; this lookup-only fixture does not + transport receipts or assert remote acceptance of locally owned events. + KERIpy owns the temporary store and removes it when the context closes. + """ + with habbing.openHby(name="issuer", temp=True) as hby: + wit = core.Signer(transferable=False).verfer.qb64 + hab = hby.makeHab(name="issuer", wits=[wit], toad=1) + yield hby, hab + + +@pytest.mark.parametrize("cold", [False, True]) +def test_current_epoch_uses_accepted_index_without_historical_walk(issuer, cold): + """Interaction history cannot make a current-epoch lookup traverse the KEL.""" + hby, hab = issuer + inception = hab.kever.serder + for _ in range(32): + hab.interact(data=[]) + sn = hab.kever.sn + if cold: + # Reload through the persisted accepted-state index, as after restart. + hby.db.kevers.clear() + kvy = Kevery(db=hby.db) + with ( + patch.object( + eventing.Kevery, + "fetchEstEvent", + side_effect=AssertionError("unexpected historical establishment walk"), + ), + patch.object( + eventing.Kevery, + "fetchWitnessState", + side_effect=AssertionError("unexpected historical witness walk"), + ), + ): + assert kvy.fetchEstEvent(hab.pre, sn).said == inception.said + assert est_event(hby.kvy, hab.pre, sn).said == inception.said + assert [wit.qb64 for wit in kvy.fetchWitnessState(hab.pre, sn)] == ( + inception.backs + ) + + +def test_rotation_keeps_older_anchors_bound_to_older_witnesses(issuer): + """Today's establishment cannot replace the key/witness authority of an old anchor.""" + hby, hab = issuer + inception = hab.kever.serder + hab.interact(data=[]) + old_sn = hab.kever.sn + old_wit = hab.kever.wits[0] + new_wit = core.Signer(transferable=False).verfer.qb64 + hab.rotate(cuts=[old_wit], adds=[new_wit], toad=1) + rotation = hab.kever.serder + hab.interact(data=[]) + kvy = Kevery(db=hby.db) + assert kvy.fetchEstEvent(hab.pre, old_sn).said == inception.said + assert est_event(hby.kvy, hab.pre, old_sn).said == inception.said + assert [wit.qb64 for wit in kvy.fetchWitnessState(hab.pre, old_sn)] == [old_wit] + assert kvy.fetchEstEvent(hab.pre, hab.kever.sn).said == rotation.said + assert [wit.qb64 for wit in kvy.fetchWitnessState(hab.pre, hab.kever.sn)] == [ + new_wit + ] + + +def test_unknown_and_future_events_keep_native_lookup_behavior(issuer): + """Cached state cannot establish acceptance of an unknown identifier or future event.""" + hby, hab = issuer + hab.interact(data=[]) + native = eventing.Kevery(db=hby.db) + kvy = Kevery(db=hby.db) + unknown = core.Signer().verfer.qb64 + for pre, sn in ((unknown, 0), (hab.pre, hab.kever.sn + 1)): + assert kvy.fetchEstEvent(pre, sn) is None + assert est_event(hby.kvy, pre, sn) is None + assert [wit.qb64 for wit in kvy.fetchWitnessState(pre, sn)] == [ + wit.qb64 for wit in native.fetchWitnessState(pre, sn) + ] + + +def test_missing_accepted_entry_is_not_inferred_from_head_state(issuer): + """A head beyond a missing KEL slot is insufficient to return an establishment.""" + hby, hab = issuer + for _ in range(4): + hab.interact(data=[]) + hby.db.delKes(dbing.snKey(hab.pre, 2)) + kvy = Kevery(db=hby.db) + native = eventing.Kevery(db=hby.db) + assert kvy.fetchEstEvent(hab.pre, 2) is None + assert est_event(hby.kvy, hab.pre, 2) is None + assert [wit.qb64 for wit in kvy.fetchWitnessState(hab.pre, 2)] == [ + wit.qb64 for wit in native.fetchWitnessState(hab.pre, 2) + ] + + +def test_missing_event_bytes_are_not_inferred_from_the_accepted_index(issuer): + """An ordinal index entry without its event cannot satisfy an event lookup.""" + hby, hab = issuer + hab.interact(data=[]) + sn, said = hab.kever.sn, hab.kever.serder.said + hby.db.delEvt(dbing.dgKey(hab.pre, said)) + assert hby.db.getKeLast(dbing.snKey(hab.pre, sn)) is not None + assert eventing.Kevery(db=hby.db).fetchEstEvent(hab.pre, sn) is None + assert Kevery(db=hby.db).fetchEstEvent(hab.pre, sn) is None + assert est_event(hby.kvy, hab.pre, sn) is None