Skip to content

Latest commit

 

History

History
980 lines (742 loc) · 38.4 KB

api.md

File metadata and controls

980 lines (742 loc) · 38.4 KB

API reference — joons_agent_guard

Version documented: 0.1.0 (joons_agent_guard.__version__). This reference was generated by reading the source under src/joons_agent_guard/; every signature below is shown exactly as inspect.signature renders it (so X | None means Optional[X], and dataclass return types appear fully qualified). The set of documented names is exactly joons_agent_guard.__all__. Every example is self-contained and runs on its own: each one works on its own short-lived temporary database, so nothing is left on disk.

Conventions shared by all three components

  • Storage. Each component wraps one sqlite3 connection to the file given as path (a str, any path-like object, or ':memory:'). The three components use separate tables, so they can share one database file. Every write runs inside an explicit BEGIN IMMEDIATE ... COMMIT transaction, so processes on the same machine serialise through SQLite file locking, and one instance may be shared between threads (a re-entrant guard lock serialises the statements of one connection).
  • timeout (constructor keyword, seconds) is SQLite's busy timeout: how long an operation waits for another process's write transaction before raising sqlite3.OperationalError: database is locked. It is never an expiry for locks, pending requests or circuit slots — those never time out.
  • Identifiers (resource, owner, job_id, actor, principal, request_id, digest, intent_id, ...) must be a non-empty str value of at most 1024 characters (MAX_IDENTIFIER_CHARS); anything else raises InvalidIdentifier.
  • Lifecycle. Every component supports the context-manager protocol (with ResourceLock(path) as lock: ... closes the connection on exit) and a close() method; using a component after close() raises sqlite3.ProgrammingError.
  • SQLite errors. Any sqlite3.Error (for example OperationalError on a busy database or a full disk) may propagate out of any method that touches the database; transactions are rolled back before it does.

Exceptions

All package errors derive from GuardError.

Exception Base classes Raised by
GuardError Exception base class; also raised directly when an apply_pending effect performs a nested write on the instance running it
InvalidIdentifier GuardError, ValueError every method that receives an identifier that is not a non-empty str
LockHeld GuardError ResourceLock.hold when the resource is already locked (attributes: resource, holder as LockInfo or None)
IntentMismatch GuardError, ValueError ReplayGuard.reserve_outbound when an intent id is reused with different content
CorruptStorage GuardError ReplayGuard.response when a stored response cannot be decoded as JSON (a corrupted or tampered database file)

Because InvalidIdentifier and IntentMismatch are also ValueError, plain except ValueError catches them. GuardError, InvalidIdentifier and IntentMismatch, CorruptStorage use the default Exception constructor (so inspect.signature has nothing to render for them); LockHeld has LockHeld(resource, holder=None) — set automatically by hold, with exc.resource and exc.holder as attributes.

import tempfile

from joons_agent_guard import LockHeld, ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    lock.acquire("deploy-api", "worker-0", "job-41")    # another holder got there first
    try:
        with lock.hold("deploy-api", owner="worker-1", job_id="job-42"):
            pass                                        # runs only if the lock was free
    except LockHeld as exc:
        print(exc.holder.owner, "has held", exc.resource)   # worker-0
    lock.close()

request_digest

request_digest(method: str, path: str, body: bytes, **fields: str) -> str

Computes the canonical digest of a request: a SHA-256 hex digest over a sorted-key JSON document containing method, path, the SHA-256 of body (as body_sha256), and every extra keyword field. The result is stable across processes and Python versions; pass the same value as the digest argument of ReplayGuard.claim, complete, response and apply_pending. Include every field that would change the meaning of the operation, and never include secrets (the digest is not a secret, but it is not encrypted either).

Parameters. method — HTTP-style verb; path — request path; body — raw request body, bytes or bytearray; **fields — additional string fields (key order does not matter).

Returns. 64-character lowercase hex string.

Raises. TypeError if body is not bytes/bytearray or any extra field value is not str; ValueError if an extra field is named body_sha256 (reserved).

from joons_agent_guard import request_digest

d1 = request_digest("POST", "/charges", b'{"order": 7}', tenant="t1")
d2 = request_digest("POST", "/charges", b'{"order": 7}', tenant="t1")
assert d1 == d2 and len(d1) == 64          # stable, 64 hex chars
assert d1 != request_digest("POST", "/charges", b'{"order": 8}', tenant="t1")

LockInfo

LockInfo(resource: str, owner: str, job_id: str, acquired_at: float) -> None

Immutable dataclass describing one held lock; you normally receive instances from ResourceLock.status, ResourceLock.list_locks and LockHeld.holder rather than constructing them.

Fields. resource — locked resource name; owner — holder identity; job_id — the holder's job; acquired_at — acquisition time as a time.time() epoch float.

import tempfile

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    assert lock.acquire("deploy-api", "worker-1", "job-42")
    info = lock.status("deploy-api")
    print(info.owner, info.job_id, info.acquired_at)   # worker-1 job-42 <epoch>
    lock.close()

ResourceLock

ResourceLock(path, *, timeout: float = 10.0)

Exclusive locks on named string resources, shared by every process (and every thread) that opens the same database file. A lock is held by an (owner, job_id) pair, survives process restarts, and never expires on its own: if the holder crashed, only the explicit, audited break_lock removes the lock. Opening the component creates the resource_locks table if needed.

Parameters. path — SQLite database file; timeout — busy timeout in seconds (default 10.0).

Raises. sqlite3.OperationalError if the file cannot be opened.

import tempfile

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    with ResourceLock(tmp + "/guard.db") as lock:      # closed automatically
        if not lock.acquire("deploy-api", "worker-1", "job-42"):
            print(lock.status("deploy-api"))           # who is holding it

ResourceLock.acquire(resource: str, owner: str, job_id: str) -> bool

Takes the exclusive lock on resource for the (owner, job_id) holder. Fails without blocking when anyone — including the same holder — already holds the resource; there is no queueing, callers retry or back off. The acquisition time recorded in the row is the basis of the age shown by the command-line tool.

Parameters. resource — name of the resource to lock; owner — stable identity of the caller (process/service); job_id — identity of this particular run.

Returns. True if this call took the lock, False if it is already held.

Raises. InvalidIdentifier; sqlite3.OperationalError on a busy or unwritable database.

import tempfile

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    if lock.acquire("deploy-api", owner="worker-1", job_id="job-42"):
        try:
            print("deploying")                 # the real work goes here
        finally:
            lock.release("deploy-api", owner="worker-1", job_id="job-42")
    lock.close()

ResourceLock.release(resource: str, owner: str, job_id: str) -> bool

Releases the lock, but only when both owner and job_id match the current holder — a stale job cannot release a lock that a new job re-acquired.

Parameters. resource, owner, job_id — must identify the current holder exactly.

Returns. True if the matching lock was removed, False otherwise (no matching holder; the lock state is unchanged).

Raises. InvalidIdentifier; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    lock.acquire("deploy-api", "worker-1", "job-42")
    assert not lock.release("deploy-api", "worker-1", "other-job")  # refused
    assert lock.release("deploy-api", "worker-1", "job-42")         # released
    lock.close()

ResourceLock.status(resource: str) -> joons_agent_guard.lock.LockInfo | None

Returns who currently holds the lock on resource, for inspection before an operator decision. Reads never block writers for long and never modify state.

Parameters. resource — resource name to inspect.

Returns. A LockInfo (resource, owner, job_id, acquired_at), or None when the resource is not locked.

Raises. InvalidIdentifier; sqlite3.OperationalError.

import tempfile
import time

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    lock.acquire("deploy-api", "worker-1", "job-42")
    info = lock.status("deploy-api")
    age = time.time() - info.acquired_at        # how long it has been held
    lock.close()

ResourceLock.list_locks() -> List[joons_agent_guard.lock.LockInfo]

Returns every lock currently held in the database, ordered by acquisition time (oldest first) — the audit view over all holders of all resources.

Parameters. None.

Returns. A list of LockInfo, oldest acquisition first (empty when nothing is held).

Raises. sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    lock.acquire("a", "owner-1", "job-1")
    lock.acquire("b", "owner-2", "job-2")
    for info in lock.list_locks():
        print(info.resource, info.owner, info.job_id)
    lock.close()

ResourceLock.break_lock(resource: str, expected_job_id: str) -> bool

Operator recovery for a holder known to be dead. Removes the lock only while the recorded job_id still equals expected_job_id, so a lock that was re-acquired by a new job in the meantime is never removed by mistake. Check status() first, confirm the holder is really gone, then break; the freed resource is immediately acquirable again.

Parameters. resource — locked resource; expected_job_id — the job id that is believed dead.

Returns. True if the matching lock was removed, False if no lock or a different job holds it now.

Raises. InvalidIdentifier; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    lock.acquire("deploy-api", "worker-1", "job-42")    # holder died; operator checked
    assert lock.break_lock("deploy-api", expected_job_id="job-42")
    assert lock.acquire("deploy-api", "worker-2", "job-43")
    lock.close()

ResourceLock.hold(resource: str, owner: str, job_id: str)

Context manager form of acquire/release: takes the lock on entry, raises LockHeld (carrying the current LockInfo in its holder attribute) when the resource is busy, and always releases on exit — including when the body raises. The body runs only if the lock was taken.

Parameters. resource, owner, job_id — as for acquire.

Returns. A context manager yielding nothing.

Raises. InvalidIdentifier; LockHeld on a busy resource; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import LockHeld, ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    lock.acquire("deploy-api", "worker-0", "job-41")
    try:
        with lock.hold("deploy-api", owner="worker-1", job_id="job-42"):
            print("deploying")                  # runs only when the lock was free
    except LockHeld as exc:
        print("busy:", exc.holder.owner)        # worker-0 holds it
    lock.close()

ResourceLock.close() -> None

Closes the underlying SQLite connection (waiting for any in-flight transaction of another thread on the same instance to finish). After this, every method raises sqlite3.ProgrammingError; the usual pattern is the context-manager form, which calls it automatically.

Parameters. None. Returns. None.

Raises. sqlite3.Error if closing fails.

import tempfile

from joons_agent_guard import ResourceLock

with tempfile.TemporaryDirectory() as tmp:
    lock = ResourceLock(tmp + "/guard.db")
    try:
        lock.acquire("deploy-api", "worker-1", "job-42")
    finally:
        lock.close()                            # connection really closed

CircuitState

CircuitState(actor: str, state: str, pending_job: str | None, consecutive_failures: int, last_failure_reason: str | None) -> None

Immutable dataclass returned by CircuitBreaker.snapshot. You normally read instances rather than constructing them.

Fields. actor — the actor this state belongs to; state — one of closed, open, half_open; pending_job — the job id currently holding the run slot, or None; consecutive_failures — failures since the last success/reset; last_failure_reason — reason string of the last failure, or None.

import tempfile

from joons_agent_guard import CircuitBreaker

with tempfile.TemporaryDirectory() as tmp:
    breaker = CircuitBreaker(tmp + "/guard.db")
    snap = breaker.snapshot("deploy-worker")
    print(snap.state, snap.pending_job, snap.consecutive_failures)
    breaker.close()

CircuitBreaker

CircuitBreaker(path, *, timeout: float = 10.0)

Durable per-actor circuit breaker with a single run slot. Each actor is in one of three states: closed (healthy; the next job may start), open (the last finished job failed; the next job that starts is the recovery attempt), half_open (a recovery attempt is running; nothing else may start). A job that started but never finished keeps its slot forever — it is never cleared by age; finish it explicitly or let an operator call reset. Opening the component creates the worker_circuits table if needed.

Parameters. path — SQLite database file; timeout — busy timeout in seconds (default 10.0).

Raises. sqlite3.OperationalError if the file cannot be opened.

import tempfile

from joons_agent_guard import CircuitBreaker

with tempfile.TemporaryDirectory() as tmp:
    with CircuitBreaker(tmp + "/guard.db") as breaker:
        if breaker.begin("deploy-worker", job_id="job-42"):
            breaker.finish("deploy-worker", "job-42", success=True)

CircuitBreaker.begin(actor: str, job_id: str) -> bool

Claims the actor's single run slot for job_id. Succeeds only when no other job is pending: while a job is pending or the actor is in half_open, every other begin returns False. When the actor is open, the successful begin is the recovery attempt and the state becomes half_open (failures and reason are kept); from closed the state stays closed with the slot held.

Parameters. actor — the worker identity; job_id — identity of the job about to run.

Returns. True if the slot was claimed, False if another job holds it.

Raises. InvalidIdentifier; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import CircuitBreaker

with tempfile.TemporaryDirectory() as tmp:
    breaker = CircuitBreaker(tmp + "/guard.db")
    if breaker.begin("deploy-worker", "job-42"):
        print("running job-42")                 # the only job for this actor
    else:
        print("slot busy:", breaker.snapshot("deploy-worker").pending_job)
    breaker.close()

CircuitBreaker.finish(actor: str, job_id: str, *, success: bool, reason: str | None = None) -> bool

Records the outcome of the pending job and frees the slot. On success the actor returns to closed with failures and reason cleared; on failure the actor becomes open, consecutive_failures increases by one and last_failure_reason is stored. Only the pending job_id may finish — anything else changes nothing.

Parameters. actor — the worker; job_id — must be the pending job; success — outcome; reason — failure description (ignored on success); a reason longer than 4096 characters (MAX_REASON_CHARS) is truncated before it is stored.

Returns. True if the outcome was recorded, False if job_id is not the pending job (state unchanged).

Raises. InvalidIdentifier; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import CircuitBreaker

with tempfile.TemporaryDirectory() as tmp:
    breaker = CircuitBreaker(tmp + "/guard.db")
    breaker.begin("deploy-worker", "job-42")
    try:
        print("deploying")                      # the real job; raise to fail it
        breaker.finish("deploy-worker", "job-42", success=True)
    except Exception as exc:
        breaker.finish("deploy-worker", "job-42", success=False, reason=str(exc))
    breaker.close()

CircuitBreaker.snapshot(actor: str) -> joons_agent_guard.circuit.CircuitState

Reads the actor's current state, pending job, consecutive failure count and last failure reason — the health view used for dashboards and for deciding whether to start work.

Parameters. actor — the worker to inspect.

Returns. A CircuitState; an actor that was never seen is reported as closed with an empty slot and zero failures.

Raises. InvalidIdentifier; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import CircuitBreaker

with tempfile.TemporaryDirectory() as tmp:
    breaker = CircuitBreaker(tmp + "/guard.db")
    snap = breaker.snapshot("deploy-worker")
    if snap.state == "half_open":
        print("recovery attempt in flight:", snap.pending_job)
    breaker.close()

CircuitBreaker.reset(actor: str, expected_job_id: str | None = None) -> bool

Operator recovery: clears the actor back to closed (slot freed, failures zeroed, reason cleared). Use it after checking what happened to a job that never finished. With expected_job_id, the reset applies only while that job is still the pending one — a guard against clearing a slot that a newer job has meanwhile taken.

Parameters. actor — the worker to clear; expected_job_id — optional job id that must still be pending for the reset to fire.

Returns. True if the actor was reset, False if nothing matched (unknown actor, or a different job is pending).

Raises. InvalidIdentifier (for actor, or for a non-empty invalid expected_job_id); sqlite3.OperationalError.

import tempfile

from joons_agent_guard import CircuitBreaker

with tempfile.TemporaryDirectory() as tmp:
    breaker = CircuitBreaker(tmp + "/guard.db")
    breaker.begin("deploy-worker", "job-42")    # the job crashed without finishing
    snap = breaker.snapshot("deploy-worker")    # operator checked: holder gone
    assert breaker.reset("deploy-worker", expected_job_id=snap.pending_job)
    assert breaker.snapshot("deploy-worker").state == "closed"
    breaker.close()

CircuitBreaker.close() -> None

Closes the underlying SQLite connection; afterwards every method raises sqlite3.ProgrammingError. The context-manager form calls it automatically.

Parameters. None. Returns. None. Raises. sqlite3.Error if closing fails.

import tempfile

from joons_agent_guard import CircuitBreaker

with tempfile.TemporaryDirectory() as tmp:
    breaker = CircuitBreaker(tmp + "/guard.db")
    try:
        breaker.begin("deploy-worker", "job-42")
    finally:
        breaker.close()

ReplayGuard

ReplayGuard(path, *, timeout: float = 15.0, max_response_bytes: int | None = 1048576)

Durable at-most-once handling of retried requests, keyed by (principal, request_id) with a content digest. claim returns new exactly once per key; a claimed request stays pending (meaning unknown: the outcome of a crashed attempt is not known, so it is never re-run or unlocked by age) until complete or apply_pending records the outcome; completed keys replay the stored response; a different digest for the same key is a conflict. The guard does not authenticate anybody: principal must come from a trusted transport, never from a client-supplied header. Opening the component creates the requests and outbound_requests tables if needed.

Parameters. path — SQLite database file; timeout — busy timeout in seconds (default 15.0 — higher than the other components because apply_pending effects run inside the write transaction); max_response_bytes — cap for one stored response as JSON, in bytes (default 1048576, i.e. 1 MiB; None disables the cap).

Raises. sqlite3.OperationalError if the file cannot be opened.

import tempfile

from joons_agent_guard import ReplayGuard, request_digest

with tempfile.TemporaryDirectory() as tmp:
    with ReplayGuard(tmp + "/guard.db") as guard:
        digest = request_digest("POST", "/charges", b'{"order": 7}')
        if guard.claim("client-a", "req-1", digest) == "new":
            guard.complete("client-a", "req-1", digest, 200, {"charged": True})

ReplayGuard.claim(principal: str, request_id: str, digest: str) -> str

The at-most-once gate. The first call for a (principal, request_id) pair inserts the request as pending (recording the claim time) and returns new — run the work. Every later call with the same digest returns pending (a previous attempt is unfinished — answer "try later", never re-run) or, after completion, completed (return the stored response). A different digest for the same pair returns conflict (the key is being reused for different work) and leaves the original claim untouched.

Parameters. principal — authenticated caller identity (namespace); request_id — the idempotency key, identical across all retries of one logical operation; digest — request_digest of the request.

Returns. One of "new", "pending", "completed", "conflict".

Raises. InvalidIdentifier; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ReplayGuard, request_digest

with tempfile.TemporaryDirectory() as tmp:
    guard = ReplayGuard(tmp + "/guard.db")
    digest = request_digest("POST", "/charges", b'{"order": 7}')
    state = guard.claim("client-a", "req-1", digest)
    if state == "new":
        guard.complete("client-a", "req-1", digest, 200, {"charged": True})
    print(state)                                # "new": run it exactly once
    guard.close()

ReplayGuard.complete(principal: str, request_id: str, digest: str, code: int, response: Any) -> bool

Stores the outcome of a pending request: state becomes completed with the given status code and the JSON-encoded response. Only a pending request with the matching digest can be completed, and only once — a second call fails, so the first response always wins. The response is stored as JSON: tuples come back as lists and non-str dict keys as strings, so use JSON-stable types. NaN and Infinity are rejected, and the JSON encoding must fit within max_response_bytes.

Parameters. principal, request_id, digest — identify the pending claim; code — integer status code stored with the response; response — any JSON-serialisable object.

Returns. True if the response was stored; False if the request is not pending with this digest (already completed, still claimed by another digest, or never claimed).

Raises. InvalidIdentifier; TypeError if code is not an int (bool is rejected) or response is not JSON-serialisable; ValueError if the response contains NaN/Infinity or its JSON encoding exceeds max_response_bytes (checked before the transaction opens); sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ReplayGuard, request_digest

with tempfile.TemporaryDirectory() as tmp:
    guard = ReplayGuard(tmp + "/guard.db")
    digest = request_digest("POST", "/charges", b'{"order": 7}')
    assert guard.claim("client-a", "req-1", digest) == "new"
    assert guard.complete("client-a", "req-1", digest, 200, {"charged": True})
    assert not guard.complete("client-a", "req-1", digest, 500, {"error": 1})
    assert guard.response("client-a", "req-1", digest) == (200, {"charged": True})
    guard.close()

ReplayGuard.response(principal: str, request_id: str, digest: str) -> Tuple[int, Any] | None

Reads back the stored response of a completed request — the value retries should return instead of re-running the work. Only completed rows with the matching digest are returned; pending or conflicting digests see nothing. A stored response that cannot be decoded as JSON raises CorruptStorage.

Parameters. principal, request_id, digest — identify the completed request.

Returns. A (code, response) tuple, or None when there is no stored response for this digest (never claimed, still pending, or a different digest).

Raises. InvalidIdentifier; CorruptStorage when the stored response cannot be decoded; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ReplayGuard, request_digest

with tempfile.TemporaryDirectory() as tmp:
    guard = ReplayGuard(tmp + "/guard.db")
    digest = request_digest("POST", "/charges", b'{"order": 7}')
    if guard.claim("client-a", "req-1", digest) == "completed":
        code, payload = guard.response("client-a", "req-1", digest)
    guard.close()

ReplayGuard.apply_pending(principal: str, request_id: str, digest: str, effect: Callable[[Any], Tuple[int, Any]]) -> Tuple[int, Any] | None

Runs a SQLite-only effect and stores its response in the same transaction — the exactly-once path. effect(connection) receives the guard's own connection inside the write transaction; it must use that connection for its SQL, must not commit, roll back or close it, and must not call write methods of the same guard instance (that raises GuardError). The effect must return an (code, response) pair; the request is marked completed and the response stored atomically with the effect's writes, so a crash or a failing effect leaves the request pending and rolls the effect back. Use it for your own new claim or an explicitly reviewed recovery of a pending request — never for files, network or subprocess effects (those cannot be atomic with the stored response).

Parameters. principal, request_id, digest — identify the pending claim; effect — callable (connection) -> (code, response); code must be an int (bool rejected).

Returns. The (code, response) pair the effect returned (the original object), or None when the request is not pending with this digest — in which case the effect never ran. Note the stored copy is JSON: later response() calls return tuples as lists.

Raises. InvalidIdentifier; GuardError on a nested write by the effect; TypeError for a non-int code; ValueError for a NaN/Infinity or oversized response (checked inside the transaction, so the effect rolls back); anything the effect raises propagates (after rollback); sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ReplayGuard, request_digest

def effect(conn):
    conn.execute("CREATE TABLE IF NOT EXISTS accounts (id INTEGER PRIMARY KEY, balance INTEGER)")
    conn.execute("UPDATE accounts SET balance = balance - 5 WHERE id = ?", (7,))
    return 200, {"charged": True}

with tempfile.TemporaryDirectory() as tmp:
    guard = ReplayGuard(tmp + "/guard.db")
    digest = request_digest("POST", "/charges", b'{"order": 7}')
    guard.claim("client-a", "req-1", digest)
    result = guard.apply_pending("client-a", "req-1", digest, effect)
    assert result == (200, {"charged": True})
    guard.close()

ReplayGuard.reserve_outbound(intent_id: str, fixed: Mapping[str, str]) -> dict

Outbound idempotency: before sending a request whose receiver deduplicates by request id, persist a stable request_id and timestamp for the business intent_id. Retrying the same intent with identical fixed content returns the identical context, so the receiver sees one request no matter how many times the delivery is retried. fixed is stored verbatim — put a body hash there, never the body or secrets. If an intent id is reused with different content, IntentMismatch is raised and the original reservation is kept.

Parameters. intent_id — the business intent's stable identity; fixed — mapping of str to str describing the request (endpoint, body hash, ...); it must not contain the reserved keys request_id or ts.

Returns. A dict containing every fixed entry plus the generated "request_id" (uuid hex) and "ts" (stringified time) — the same dict on every retry.

Raises. InvalidIdentifier; TypeError if fixed is not a Mapping with str keys and str values; ValueError if fixed contains request_id or ts; IntentMismatch on reuse with different content; sqlite3.OperationalError.

import tempfile

from joons_agent_guard import ReplayGuard

with tempfile.TemporaryDirectory() as tmp:
    guard = ReplayGuard(tmp + "/guard.db")
    ctx = guard.reserve_outbound("email-batch-77",
                                 {"to": "ops@example.com", "body_sha256": "9f2c" * 16})
    assert guard.reserve_outbound("email-batch-77",
                                  {"to": "ops@example.com", "body_sha256": "9f2c" * 16}) == ctx
    print("sending with request_id", ctx["request_id"])   # a retry gets the same id
    guard.close()

ReplayGuard.close() -> None

Closes the underlying SQLite connection; afterwards every method raises sqlite3.ProgrammingError. The context-manager form calls it automatically.

Parameters. None. Returns. None. Raises. sqlite3.Error if closing fails.

import tempfile

from joons_agent_guard import ReplayGuard, request_digest

with tempfile.TemporaryDirectory() as tmp:
    guard = ReplayGuard(tmp + "/guard.db")
    digest = request_digest("POST", "/charges", b'{"order": 7}')
    try:
        guard.claim("client-a", "req-1", digest)
    finally:
        guard.close()                           # connection really closed

AsyncResourceLock

AsyncResourceLock(path, *, timeout: float = 10.0)

Coroutine wrapper around ResourceLock: it owns one synchronous instance and dispatches every blocking call with asyncio.to_thread (Python 3.9+), so a contended SQLite write waits on a worker thread while the event loop keeps running. The method names and semantics match the synchronous class, but the methods are coroutines; hold becomes an async context manager, and aclose() / async with close the owned instance. The constructor is synchronous and creates the schema on the calling thread. Cancelling an in-flight call ends the task promptly with CancelledError while the SQLite operation finishes on the thread; the outcome stays queryable via status / release (see the aio.py module docstring).

Methods. acquire(resource: str, owner: str, job_id: str) -> bool, release(resource: str, owner: str, job_id: str) -> bool, status(resource: str) -> joons_agent_guard.lock.LockInfo | None, list_locks() -> List[joons_agent_guard.lock.LockInfo], break_lock(resource: str, expected_job_id: str) -> bool, hold(resource: str, owner: str, job_id: str) (async context manager), aclose() -> None — each mirrors the synchronous method of the same name and raises the same exceptions (InvalidIdentifier, LockHeld on a busy hold, sqlite3.OperationalError).

Example.

import asyncio
import tempfile

from joons_agent_guard import AsyncResourceLock

async def main():
    with tempfile.TemporaryDirectory() as tmp:
        async with AsyncResourceLock(tmp + "/guard.db") as lock:
            if await lock.acquire("deploy-api", "worker-1", "job-42"):
                print("deploying")                 # the call runs on a worker thread
                await lock.release("deploy-api", "worker-1", "job-42")

asyncio.run(main())

AsyncCircuitBreaker

AsyncCircuitBreaker(path, *, timeout: float = 10.0)

Coroutine wrapper around CircuitBreaker: one synchronous instance per adapter, every blocking call dispatched with asyncio.to_thread, same method names and semantics as coroutines, aclose() / async with lifecycle, and the same constructor notes as AsyncResourceLock above.

Methods. begin(actor: str, job_id: str) -> bool, finish(actor: str, job_id: str, *, success: bool, reason: str | None = None) -> bool (a reason longer than 4096 characters is truncated before storage), snapshot(actor: str) -> joons_agent_guard.circuit.CircuitState, reset(actor: str, expected_job_id: str | None = None) -> bool, aclose() -> None — each mirrors the synchronous method of the same name and raises the same exceptions (InvalidIdentifier, sqlite3.OperationalError).

Example.

import asyncio
import tempfile

from joons_agent_guard import AsyncCircuitBreaker

async def main():
    with tempfile.TemporaryDirectory() as tmp:
        async with AsyncCircuitBreaker(tmp + "/guard.db") as breaker:
            if await breaker.begin("deploy-worker", "job-42"):
                await breaker.finish("deploy-worker", "job-42", success=True)

asyncio.run(main())

AsyncReplayGuard

AsyncReplayGuard(path, *, timeout: float = 15.0)

Coroutine wrapper around ReplayGuard: one synchronous instance per adapter, every blocking call dispatched with asyncio.to_thread, same method names and semantics as coroutines, aclose() / async with lifecycle. An apply_pending effect is a plain sync function running on the worker thread inside the write transaction; it must not use asyncio.

Methods. claim(principal: str, request_id: str, digest: str) -> str, complete(principal: str, request_id: str, digest: str, code: int, response: Any) -> bool, response(principal: str, request_id: str, digest: str) -> Tuple[int, Any] | None (raises CorruptStorage on an undecodable stored response), apply_pending(principal: str, request_id: str, digest: str, effect: Callable[[Any], Tuple[int, Any]]) -> Tuple[int, Any] | None, reserve_outbound(intent_id: str, fixed: Mapping[str, str]) -> dict, aclose() -> None — each mirrors the synchronous method of the same name and raises the same exceptions, including the ValueError for a NaN/Infinity or oversized response and the max_response_bytes cap.

Example.

import asyncio
import tempfile

from joons_agent_guard import AsyncReplayGuard, request_digest

async def main():
    with tempfile.TemporaryDirectory() as tmp:
        async with AsyncReplayGuard(tmp + "/guard.db") as guard:
            digest = request_digest("POST", "/charges", b'{"order": 7}')
            state = await guard.claim("client-a", "req-1", digest)
            if state == "new":
                await guard.complete("client-a", "req-1", digest, 200, {"charged": True})
            print(state, await guard.response("client-a", "req-1", digest))

asyncio.run(main())

Command line tool

python -m joons_agent_guard --db PATH [--json] COMMAND ... is an operator tool over the same database file. The read commands (locks, circuit, pending) only run SELECT statements — they never create tables, claim requests or change state — and tolerate a database that never used a component. They open the database strictly read-only (mode=ro plus PRAGMA query_only), so nothing on disk is created or modified and a crashed writer's hot journal is reported as an error instead of being silently rolled back. The two recovery commands (break-lock, reset-circuit) call the library's audited API and only act when --yes is given; without it they print what would happen and exit 2.

Global options. --db PATH (required) — the guard's SQLite database file; --json — machine-readable JSON instead of plain text (both flags are accepted before or after the command).

Command Arguments Effect
locks — lists held locks: resource, owner, job_id, age
circuit ACTOR prints one actor's snapshot (state, pending job, failures, reason); exit 1 if no circuit is recorded for the actor
pending [--older-than SECONDS] read-only list of replay requests in state pending: principal, request_id, digest prefix, age; with --older-than, only requests whose recorded claim time is at least that old (rows without a claim time are never listed by it)
break-lock RESOURCE --job-id ID [--yes] without --yes prints what would happen (exit 2); with --yes removes the lock only if the current holder's job_id matches (exit 1 if nothing matched)
reset-circuit ACTOR [--job-id ID] [--yes] without --yes prints what would happen (exit 2); with --yes resets the actor to closed, optionally only while the given job is still pending (exit 1 if nothing matched)

Age is information for the operator, never a reason to re-run anything automatically: pending still means "unknown".

Exit codes. 0 ok; 1 not found / nothing changed (unknown actor, database file missing, a recovery operation that matched nothing); 2 confirmation required or bad usage (recovery command without --yes, unknown command, missing arguments, negative --older-than).

In-process use. The same parser is reachable as cli.main(argv: List[str] | None = None) -> int from joons_agent_guard.cli; it returns the exit code instead of exiting.

python -m joons_agent_guard --db guard.db locks
python -m joons_agent_guard --db guard.db circuit deploy-worker
python -m joons_agent_guard --db guard.db pending --older-than 3600 --json
python -m joons_agent_guard --db guard.db break-lock deploy-api --job-id job-42          # plan only, exit 2
python -m joons_agent_guard --db guard.db break-lock deploy-api --job-id job-42 --yes    # apply
python -m joons_agent_guard --db guard.db reset-circuit deploy-worker --yes