Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(vault): give approval continuation one crash-safe owner (#2778)

Call Whitea5ea210b3233
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index d1461bd67..34d1fa12e 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -938,12 +938,14 @@ def enqueue_session_callback(
source_session_id: Optional[str] = None,
parent_run_id: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
+ run_id: Optional[str] = None,
) -> Optional["TaskExecutionRequest"]:
"""Enqueue a callback turn into an existing agent session — the shared entry used by Agent
Run / watch / scheduled-task callbacks and vault-request auto-resume. Resolves the session's
agent/backend/model target and enqueues an ``agent_run`` with ``source_kind="callback"`` so
the running scheduler dispatches it. Returns ``None`` when there is nothing to send;
``resolve_session_id_target`` raises for an unresolvable/archived session (caller handles).
+ A caller that recorded ``run_id`` durably before calling gets that Run back on a repeat.
"""
session_id = (session_id or "").strip()
if not session_id or not (message or "").strip():
@@ -974,6 +976,7 @@ def enqueue_session_callback(
**({"callback_parent_run_id": parent_run_id} if parent_run_id else {}),
},
callback_parent_to_arm=parent_run_id,
+ run_id=run_id,
)
@@ -2552,6 +2555,34 @@ class TaskExecutionStore:
write_atomic(path, json.dumps(request.to_dict(), indent=2))
return request
+ def _enqueue_identified_run(
+ self,
+ request: TaskExecutionRequest,
+ *,
+ expected_enabled_agent_id: Optional[str],
+ ) -> TaskExecutionRequest:
+ """Insert a caller-owned identity without ever resetting an existing Run."""
+
+ if self._sqlite is not None:
+ self._sqlite.enqueue_run(
+ self.queued_run_payload(request),
+ expected_enabled_agent_id=expected_enabled_agent_id,
+ if_absent=True,
+ )
+ stored = self._sqlite.get_run(request.id)
+ else:
+ from storage.lock import MigrationFileLock
+
+ # File-backed producers also serialize their final check and write. Keep
+ # this inode: another store/process may already be waiting on it.
+ with MigrationFileLock(self.root / "identified-enqueue.lock", timeout_seconds=None):
+ stored = self.get_run(request.id)
+ if stored is None:
+ return self.enqueue(request, expected_enabled_agent_id=expected_enabled_agent_id)
+ if stored is None:
+ raise RuntimeError(f"Identified Run {request.id} was not persisted")
+ return TaskExecutionRequest.from_dict(stored)
+
def enqueue_task_run(
self,
task_id: str,
@@ -2801,6 +2832,7 @@ class TaskExecutionStore:
metadata: Optional[dict[str, Any]] = None,
expected_enabled_agent_id: Optional[str] = None,
callback_parent_to_arm: Optional[str] = None,
+ run_id: Optional[str] = None,
) -> Optional[TaskExecutionRequest]:
if not (message or "").strip():
# Refuse at the door: a blank prompt never reaches an agent backend
@@ -2808,13 +2840,19 @@ class TaskExecutionStore:
# by a terminal result. Every caller (CLI, callback, delivery) has a
# real message; a blank one is a bug in the caller.
raise ValueError("agent run requires a non-empty message")
+ if run_id:
+ # The caller fixed this identity before enqueueing, so a repeat after an
+ # interruption is the same Run, never a second one.
+ existing = self.get_run(run_id)
+ if existing is not None:
+ return TaskExecutionRequest.from_dict(existing)
normalized_delivery_intent = normalize_agent_run_delivery_intent(delivery_intent)
if str(delivery_intent or "").strip().lower() == AGENT_RUN_DELIVERY_SEND_NOW:
normalized_delivery_intent = AGENT_RUN_DELIVERY_SEND_NOW
run_metadata = dict(metadata or {})
run_metadata[AGENT_RUN_DELIVERY_INTENT_METADATA_KEY] = normalized_delivery_intent
request = TaskExecutionRequest(
- id=uuid4().hex[:12],
+ id=run_id or uuid4().hex[:12],
request_type="agent_run",
session_key=session_key,
session_id=session_id,
@@ -2871,10 +2909,15 @@ class TaskExecutionStore:
parent_status = _normalize_requested_run_status(parent.get("status"))
if bool(parent.get("cancel_requested")) and parent_status != "canceled":
return None
- queued = self.enqueue(
- request,
- expected_enabled_agent_id=expected_enabled_agent_id,
- )
+ if run_id:
+ queued = self._enqueue_identified_run(
+ request, expected_enabled_agent_id=expected_enabled_agent_id
+ )
+ else:
+ queued = self.enqueue(
+ request,
+ expected_enabled_agent_id=expected_enabled_agent_id,
+ )
if normalized_callback_parent:
self.update_callback_status(
normalized_callback_parent,
@@ -7727,20 +7770,25 @@ class ScheduledTaskService:
# Runs every tick, so use the process-local cached engine (never dispose it) rather than
# allocating a fresh engine per sweep.
engine = get_cached_sqlite_engine(paths.get_sqlite_state_path())
- try:
+
+ def load_pending() -> list[dict[str, Any]]:
with engine.begin() as conn:
# Expiry is lazy (only on request reads), so proactively expire overdue pending
# requests here — otherwise an unattended timed-out request would never arm its
# callback until some unrelated read touched it. Both happen in one pass.
vault_service.expire_overdue_requests(conn)
- pending = vault_service.list_pending_request_callbacks(conn)
+ return vault_service.list_pending_request_callbacks(conn)
+
+ try:
+ # Off the controller loop: these are write transactions that can wait for SQLite's lock.
+ pending = await self._run_runtime_sync(load_pending)
except Exception as exc:
logger.error("Vault request callback sweep failed to load: %s", exc, exc_info=True)
return
for row in pending:
# Keep the legacy drain aligned with the runtime-work processor, including completed
# waiter outcomes that belong in the transcript without starting another Agent turn.
- status = self._process_vault_callback_sync(row)
+ status = await self._run_runtime_sync(self._process_vault_callback_sync, row)
if status == "sent":
# A callback run was enqueued into the run store; drain it promptly.
self._wake_runtime_work(RuntimeWorkLane.REQUESTS)
@@ -7809,55 +7857,70 @@ class ScheduledTaskService:
if not request_id:
return "skipped"
engine = get_cached_sqlite_engine(paths.get_sqlite_state_path())
- status = "skipped"
try:
+ # Decide on the CURRENT row, never the scan snapshot: a waiter may have armed,
+ # completed, or died since the scan, and only this decision can see that.
with engine.begin() as conn:
- ready = vault_service.request_callback_ready(conn, row)
- if not ready:
- return "pending"
- plan = vault_service.resolve_request_callback(row)
- if plan is not None:
- request_type = str(row.get("request_type") or "")
- request_status = str(row.get("status") or "")
- if vault_service.request_callback_consumed_by_waiter(row):
- from core.message_mirror import mirror_vault_waiter_outcome
-
- mirrored = mirror_vault_waiter_outcome(
- session_id=plan.session_id,
- request_id=request_id,
- request_type=request_type,
- request_status=request_status,
- message=plan.message,
- )
- if not mirrored:
- # The stable native message id makes this mirror safe to retry. Keep the
- # callback pending so a transient SQLite/dispatch failure is retried by
- # the next sweep instead of losing the waiter's transcript outcome.
- logger.warning("failed to persist Vault waiter outcome for %s; will retry", request_id)
- return "pending"
- else:
- callback_metadata: dict[str, Any] = {
- "vault_request_type": request_type,
- "vault_request_status": request_status,
- }
- # Auto-resume is deferred work the requesting caller
- # authorized, so it travels under the authority that was
- # recorded when the request row was created — the same rule
- # a Run's callback follows. Re-deriving it inside the
- # daemon would resume a remote caller's session as local.
- from storage.resource_access_service import RESOURCE_USER_CONTEXT_METADATA_KEY
-
- requester_context = vault_service.request_authorization_snapshot(row)
- if requester_context:
- callback_metadata[RESOURCE_USER_CONTEXT_METADATA_KEY] = requester_context
- enqueue_session_callback(
- self.request_store,
- session_id=plan.session_id,
- message=plan.message,
- source_actor=f"vault:{request_id}",
- metadata=callback_metadata,
- )
- status = "sent"
+ claim = vault_service.claim_request_callback(conn, request_id)
+ except Exception as exc:
+ # Nothing landed, so nothing was decided; the next pass decides again.
+ logger.error("Vault request callback claim failed for %s: %s", request_id, exc, exc_info=True)
+ return "pending"
+ if claim.action == "defer":
+ return "pending"
+ if claim.action == "settled" or claim.row is None or claim.plan is None:
+ # Already decided by an earlier pass (or nothing is owed): report what was recorded.
+ recorded = str((claim.row or {}).get("callback_status") or "")
+ return recorded if recorded in {"sent", "skipped", "failed"} else "skipped"
+ if claim.released_waiter_id:
+ vault_service.discard_request_waiter_lock(engine, claim.released_waiter_id)
+ current, plan = claim.row, claim.plan
+ status = "skipped"
+ try:
+ request_type = str(current.get("request_type") or "")
+ request_status = str(current.get("status") or "")
+ if claim.action == "mirror":
+ from core.message_mirror import mirror_vault_waiter_outcome
+
+ mirrored = mirror_vault_waiter_outcome(
+ session_id=plan.session_id,
+ request_id=request_id,
+ request_type=request_type,
+ request_status=request_status,
+ message=plan.message,
+ )
+ if not mirrored:
+ # The stable native message id makes this mirror safe to retry. Keep the
+ # callback pending so a transient SQLite/dispatch failure is retried by
+ # the next sweep instead of losing the waiter's transcript outcome.
+ logger.warning("failed to persist Vault waiter outcome for %s; will retry", request_id)
+ return "pending"
+ else:
+ callback_metadata: dict[str, Any] = {
+ "vault_request_type": request_type,
+ "vault_request_status": request_status,
+ }
+ # Auto-resume is deferred work the requesting caller
+ # authorized, so it travels under the authority that was
+ # recorded when the request row was created — the same rule
+ # a Run's callback follows. Re-deriving it inside the
+ # daemon would resume a remote caller's session as local.
+ from storage.resource_access_service import RESOURCE_USER_CONTEXT_METADATA_KEY
+
+ requester_context = vault_service.request_authorization_snapshot(current)
+ if requester_context:
+ callback_metadata[RESOURCE_USER_CONTEXT_METADATA_KEY] = requester_context
+ # The claim recorded this Run id before enqueueing, so a pass that stopped
+ # between enqueue and the ``sent`` mark finds its Run instead of adding one.
+ enqueue_session_callback(
+ self.request_store,
+ session_id=plan.session_id,
+ message=plan.message,
+ source_actor=f"vault:{request_id}",
+ metadata=callback_metadata,
+ run_id=claim.run_id,
+ )
+ status = "sent"
except ValueError:
status = "skipped"
except Exception as exc:
diff --git a/docs/plans/2026-10-17-vault-continuation-ownership.md b/docs/plans/2026-10-17-vault-continuation-ownership.md
new file mode 100644
index 000000000..4dfa9b6ba
--- /dev/null
+++ b/docs/plans/2026-10-17-vault-continuation-ownership.md
@@ -0,0 +1,201 @@
+# Vault approval continuation ownership
+
+## Problem and cause
+
+A protected `vault run` or `vault fetch` can wait synchronously for browser
+approval while the same request retains an asynchronous Session callback.
+The callback currently treats `waiter.status == active` plus a future deadline
+as proof that the CLI still owns continuation. A command killed before that
+deadline leaves a durable but ownerless waiter, delaying a ready approval.
+
+The synchronous wait/gate shipped in #826 (2026-07-07). The later agent-core
+Bash/job lifecycle (#2345, 2026-10-04) supplies another concrete interruption
+path: a caller-selected command timeout can precede the approval timeout.
+The foreground handover window is not itself a command-kill timeout.
+
+A second boundary must be fixed with the first: callback processing uses a
+previously scanned row, while CLI waiter arm/completion happens independently.
+Liveness without serialized, fresh ownership decisions still permits duplicate
+continuations.
+
+## Change contract
+
+Preserve the shipped synchronous `run`/`fetch` default and explicit wait flags.
+Do not remove real terminal/CLI behavior, special-case an Agent backend, or
+change job/Watch timeouts to hide the defect. The shared Vault boundary owns
+continuation arbitration; the job layer only owns command execution.
+
+1. A live synchronous owner suppresses an asynchronous Agent callback. A date
+ or an unverified PID alone is not proof of ownership.
+2. A process-bound ownership primitive is released by the OS on process death,
+ including forced kill. Signal handlers, best-effort cleanup and heartbeat
+ timing must not be the correctness foundation. Prefer the existing portable
+ cross-process lock implementation over a new lease subsystem.
+3. CLI arm/completion and callback takeover are serialized and re-read durable
+ state at the decision point. Once callback continuation is durably selected,
+ a late or resumed CLI must not execute the approved operation. Daemon recovery
+ must not reopen that decision after enqueue-before-mark interruption.
+4. A successfully consumed synchronous approval remains transcript-only; it
+ must not start a second Agent turn. Approval consumption is not a claim that
+ the downstream command has completed.
+5. A dead owner's ready request becomes eligible on the next callback processing
+ pass, not its old approval deadline. A still-live owner survives service
+ restart without being mistaken for dead. Holding a lock must not block the
+ controller event loop or keep a SQLite transaction open while awaiting a user.
+6. Grant delivery readiness, authorization snapshots and one-shot grant rules
+ remain authoritative. Callback enqueue is idempotent across the enqueue/mark
+ crash window: `source_actor` alone is currently only a label for Vault
+ callbacks, not a deduplication guarantee. Reuse durable Run identity and the
+ existing request store rather than add a parallel queue. Preserve the existing
+ suppression of covered sibling callbacks when a synchronous owner completes.
+ Separate requests are not merged merely because they share a grant: a grant
+ authorizes access, not the identity of an operation to execute.
+7. Released waiter rows without ownership evidence need an explicit bounded
+ compatibility policy. Missing historical proof is not evidence of death;
+ do not release possibly live old waiters by guessing.
+8. Do not automatically replay a command whose effects may already have started.
+ This is approval continuation arbitration, not an exactly-once guarantee for
+ arbitrary external side effects.
+
+## Validation
+
+Existing tests exercise graceful completion and timeout, not an abruptly dead
+CLI with a future deadline. The primary regression must kill a real test-owned
+waiting process, approve in isolated state, and prove prompt callback eligibility.
+It must fail on the base revision for the stale-waiter gate, not setup failure.
+
+Additional distinct risks:
+
+- A live waiter, including a handed-over command, still suppresses callback.
+- Explicit wait and no-wait CLI behavior remain compatible for run and fetch.
+- Completion versus callback takeover, and approval before waiter arming, cannot
+ select both continuations, including use of a stale scheduler scan row.
+- Callback enqueue followed by daemon interruption cannot hand execution back
+ to a new CLI waiter.
+- Dead-owner recovery and live-owner preservation across a service instance
+ change are distinguished.
+- Approval without a delivery-ready grant still waits.
+- Covered siblings preserve the existing synchronous-owner suppression, and
+ repeated processing of the same request does not create duplicate Agent turns.
+- Legacy records follow the documented bounded rollout policy.
+
+Tests use temporary homes/databases and only processes they start; no real
+secrets, live approvals, installed runtime changes or service restarts.
+Focused Python tests and changed-file Ruff precede CI/exact-head review.
+
+## Implementation constraints
+
+- Use a kernel-held lock as new waiter liveness evidence and conditional database
+ updates (checking the affected-row count) as the continuation fence. These have
+ different responsibilities; neither replaces the other.
+- The callback must durably claim continuation even when no waiter has yet been
+ armed. Merely testing `callback_status != sent` leaves a create/arm versus
+ enqueue/mark window. A CLI losing either arm or completion must not deliver.
+- Read the current row at the ownership decision, not a scan snapshot. Preserve
+ current provision-field projection when refreshing callback data.
+- Lock paths must be derived from the database/instance being protected, not
+ an unrelated ambient home; validate identifiers before path construction.
+ Do not unlink a lock inode while another claimant could hold or acquire it.
+- Legacy unproven waiters retain their existing bounded deadline behavior for
+ rollout; new waiters must not use that deadline as liveness evidence.
+- Align the bundled Vault Skill with real synchronous success versus deferred
+ continuation behavior; do not tell the Agent to replay a successful command.
+
+## Finalized state shape
+
+All new state lives in the existing `vault_requests.delivery` JSON; there is no
+schema migration.
+
+```json
+"waiter": {
+ "id": "vw_<12 lowercase hex>",
+ "status": "active | completed | timed_out | abandoned",
+ "liveness": "lock",
+ "deadline_at": "<ISO-8601>",
+ "updated_at": "<ISO-8601>",
+ "completed_at | timed_out_at | abandoned_at": "<ISO-8601>"
+},
+"continuation": {"owner": "callback", "run_id": "<12 hex>", "claimed_at": "<ISO-8601>"}
+```
+
+- `waiter.liveness == "lock"` marks a new waiter whose liveness evidence is the
+ OS lock at `<directory of the resolved SQLite database>/vault-waiters/<id>.lock`.
+ The CLI acquires it through `storage.lock.MigrationFileLock` (zero timeout)
+ before committing the arm and holds it until after its terminal commit.
+ `deadline_at` remains the CLI's own declared wait bound.
+- The daemon inspects that lock without creating it. `held` means live and
+ `free` means the owner process is gone. `missing` or an inspection error is
+ never treated as death: the owner stays presumed live until its own declared
+ `deadline_at`, after which takeover still goes through the fence below.
+- A waiter without `liveness` is a released row shape. It stays live until its
+ recorded `deadline_at`, exactly as before; it is never presumed dead early.
+- `continuation` is the callback's durable claim and `run_id` is the callback
+ Run's id. One request has at most one waiter and at most one claim.
+
+Every transition runs in a write-reserved transaction, re-reads the row, and
+applies a conditional update on the read `delivery` text, requiring one
+affected row:
+
+| Transition | Actor | Requires | Writes |
+| --- | --- | --- | --- |
+| arm | CLI | no waiter, no continuation, `callback_status != 'sent'` | `waiter` active |
+| complete | CLI | own waiter active, no continuation, `callback_status != 'sent'` | waiter completed; unclaimed covered siblings skipped |
+| time out | CLI | own waiter active | waiter timed_out |
+| claim | daemon | `callback_status == 'pending'`, no continuation, waiter absent/timed_out/abandoned or active but not live, delivery-ready gate, a callback plan | `continuation` (and an active dead waiter becomes abandoned) |
+
+A CLI that loses arm or complete returns `approval_handed_off` and delivers
+nothing. After a claim the daemon enqueues the callback Run with `run_id`; an
+existing Run with that id is reused, so a restart between enqueue and the
+conditional `pending -> sent` mark re-enters with the same identity. A completed
+waiter is mirrored to the transcript only. A row without a callback plan is
+marked `skipped` and keeps no claim, so its waiter may still complete.
+
+The lock file is removed only by a process that holds it after the waiter is
+terminal in the database: the CLI after its own terminal commit, or the daemon
+after it claimed a dead owner's request. No later claimant exists for a
+terminal waiter id. A CLI exiting without a terminal commit releases without
+unlinking, so the next pass sees `free`. Windows refuses to unlink an open
+file, so there the file is left behind.
+
+Mixed versions: a released daemon neither inspects locks nor writes claims. It
+keeps deferring a new waiter until `deadline_at`, and a new CLI refuses to arm
+or complete once that daemon has marked `sent`. A released daemon's own
+enqueue-before-mark window and a released CLI's unconditional completion are not
+closed by this change.
+
+## Status
+
+Implemented on `fix/vault-continuation-ownership`; not yet published or reviewed.
+
+- `storage/vault_service.py` owns the arbitration: `arm_request_waiter`,
+ `complete_request_waiter`, `timeout_request_waiter` and
+ `claim_request_callback` are the only writers of `waiter` and `continuation`.
+ `storage/lock.py` adds the non-creating lock inspection and the
+ holder-only removal.
+- `core/scheduled_tasks.py` processes each request through
+ `claim_request_callback` and enqueues with the claimed Run id. Caller-fixed
+ identities use insert-only arbitration in `storage/background.py`, under the
+ SQLite writer reservation, rather than the ordinary Run upsert. The file
+ backend similarly serializes its final lookup and insertion with an OS lock.
+ An early lookup is only an optimization; a concurrently started or completed
+ Run can never be rewritten to `queued`. The periodic Vault callback drain runs
+ its SQLite work on the runtime-work executor instead of the controller loop.
+ A failed claim leaves the request pending for the next pass rather than marking
+ it failed.
+- `vibe/cli.py` holds the waiter lock for the whole wait and returns
+ `approval_handed_off` without delivering when it loses arm or completion.
+- `skills/use-avibe-vault/SKILL.md` (0.5.0) tells the Agent not to rerun a
+ successful command, and to rerun once after a resume when the command did not run.
+
+The primary regression starts a real `vibe vault run`, hard-kills it with its
+deadline more than five minutes away, approves, and requires the next callback
+pass to send. On the base revision that pass returned `pending`. The stale-scan
+and enqueue-before-mark regressions also fail on the base revision with a
+second callback Run. Independent review additionally reproduced a stale-absence
+race against the first implementation: a competing producer completed the same
+fixed-id Run after an initial missing lookup, and the ordinary upsert reset it to
+`queued` (or recreated its pending file). The regression fails on that version
+for both SQLite and file stores and passes with insert-only arbitration. Crash
+replay is also exercised through both stores, not only the legacy file backend.
+
+No runtime deployment or restart is authorized by this change.
diff --git a/skills/use-avibe-vault/SKILL.md b/skills/use-avibe-vault/SKILL.md
index e81df821b..7cc963d77 100644
--- a/skills/use-avibe-vault/SKILL.md
+++ b/skills/use-avibe-vault/SKILL.md
@@ -2,7 +2,7 @@
name: use-avibe-vault
slug: use-avibe-vault
description: Use Avibe Vault for API keys, tokens, passwords, protected credentials, authenticated HTTP requests, or digest signing without exposing secret values to the agent.
-version: 0.4.0
+version: 0.5.0
---
# Use Avibe Vault
@@ -24,7 +24,7 @@ Rules:
- `list` and `find` return value-free `default_field` and `fields` metadata. If a ref fails with `field_not_found`, use the listed field names rather than guessing.
- `export` remains deprecated and has no delivery. Prefer `run`; advanced `inject` writes a restricted-permission file, so use it only for tools that require file-based configuration.
- With `vibe vault run`, the child process receives static secrets as environment variables, so never run commands that may print env vars, debug config, or secret-bearing errors.
-- When protected `run` / `fetch` needs approval, Avibe automatically asks the user to decrypt and authorize access. After the user approves, Avibe resumes this session; it does not replay the command for you, so run the same `run` / `fetch` command again.
+- When protected `run` / `fetch` needs approval, Avibe automatically asks the user to decrypt and authorize access, and the command waits for that approval (540 seconds by default; `--approval-wait SECONDS` or `--no-approval-wait` to change it). If the command then succeeds, it ran once: do not run it again. If it returns `approval_required`, `approval_wait_timeout`, or `approval_handed_off`, or your call to it is stopped before it gets the approval, the command did not run; Avibe resumes this session once the request is decided, and after an approval you run the same `run` / `fetch` command once.
- When protected `sign` needs approval, Avibe creates a browser signing request and returns immediately. Do not rerun `sign`; when Avibe resumes this session, follow the callback instruction to read the completed request result and continue with the returned signature.
Common commands:
diff --git a/storage/background.py b/storage/background.py
index 12e461547..fa9e03e6a 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -4114,11 +4114,18 @@ class SQLiteBackgroundTaskStore:
*,
expected_enabled_agent_id: Optional[str] = None,
expected_reference_agent_id: Optional[str] = None,
+ if_absent: bool = False,
) -> None:
values = self._run_values(payload)
with run_update_event_transaction(self.engine) as conn:
- if expected_enabled_agent_id is not None or expected_reference_agent_id is not None:
+ if if_absent or expected_enabled_agent_id is not None or expected_reference_agent_id is not None:
reserve_write_lock(conn)
+ if if_absent and conn.execute(
+ select(agent_runs.c.id).where(agent_runs.c.id == values["id"])
+ ).scalar_one_or_none() is not None:
+ # A caller-fixed identity is insert-only. The ordinary enqueue helper
+ # upserts, which would reset a concurrently started/completed Run to queued.
+ return
if expected_enabled_agent_id is not None:
_require_enabled_agent_identity(
conn,
diff --git a/storage/lock.py b/storage/lock.py
index 5cb4a46e5..e596472f8 100644
--- a/storage/lock.py
+++ b/storage/lock.py
@@ -6,7 +6,7 @@ import threading
import time
from pathlib import Path
from types import TracebackType
-from typing import Callable, IO, Optional, Type
+from typing import Callable, IO, Literal, Optional, Type
logger = logging.getLogger(__name__)
@@ -313,6 +313,68 @@ def _unlock(handle) -> None:
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
+#: What a look at another process's lock established, without creating or keeping
+#: it: a live handle holds it, nothing does, there is no file, or the look failed.
+LockHolderState = Literal["held", "free", "missing", "unknown"]
+
+
+def probe_lock_holder(lock_path: Path) -> LockHolderState:
+ """Whether a live handle holds the lock at ``lock_path``, leaving the path as found.
+
+ The OS drops a lock when its holding process ends, however it ends, so ``free``
+ is evidence that the holder is gone. The path is never created: a lock that is
+ not there names no holder either way, so ``missing`` and ``unknown`` are
+ reported rather than guessed. Windows answers a failed attempt the same way as
+ a held lock, so there an inspection error reads as ``held``, never ``free``.
+ """
+
+ try:
+ handle = open(lock_path, "r+", encoding="utf-8")
+ except FileNotFoundError:
+ return "missing"
+ except OSError:
+ return "unknown"
+ try:
+ handle.seek(0)
+ if not _try_lock(handle):
+ return "held"
+ _unlock(handle)
+ return "free"
+ except OSError:
+ return "unknown"
+ finally:
+ handle.close()
+
+
+def remove_unheld_lock(lock_path: Path) -> bool:
+ """Delete ``lock_path`` while holding its lock, when no live handle holds it.
+
+ Only for a lock that no later claimant will take again. Unlinking under our own
+ lock then cannot split two claimants across an old and a new inode. Best effort:
+ Windows refuses to delete an open file, which leaves the file in place.
+ """
+
+ try:
+ handle = open(lock_path, "r+", encoding="utf-8")
+ except OSError:
+ return False
+ try:
+ handle.seek(0)
+ if not _try_lock(handle):
+ return False
+ try:
+ lock_path.unlink()
+ return True
+ except OSError:
+ return False
+ finally:
+ _unlock(handle)
+ except OSError:
+ return False
+ finally:
+ handle.close()
+
+
def fcntl_available() -> bool:
try:
import fcntl # noqa: F401
diff --git a/storage/vault_service.py b/storage/vault_service.py
index fed562a89..708c0a342 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -23,6 +23,7 @@ import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from functools import lru_cache
+from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
@@ -32,6 +33,7 @@ from sqlalchemy.engine import Connection
from sqlalchemy.exc import IntegrityError
from storage import vault_crypto, vault_webauthn
+from storage.lock import LockHolderState, MigrationFileLock, probe_lock_holder, remove_unheld_lock
from storage.models import (
agent_sessions,
scopes,
@@ -1453,16 +1455,124 @@ def _request_waiter(delivery: Any) -> dict[str, Any]:
return waiter if isinstance(waiter, dict) else {}
-def _request_waiter_active(row: dict[str, Any]) -> bool:
- _, delivery = _request_json_payloads(row)
- waiter = _request_waiter(delivery)
+# --- Approval continuation ownership ---------------------------------------------------------
+#
+# An approved request continues exactly one way: a synchronous CLI waiter consumes it in the
+# command that asked, or the daemon resumes the requesting Session with a callback turn. Both
+# sides decide inside a write-reserved transaction on the CURRENT row and land their decision
+# with an update conditional on the ``delivery`` text they read, so neither can act on a
+# decision the other has already made. A new waiter proves it is alive by holding an OS lock
+# beside the database it waits in; the OS drops that lock when the process ends, however it
+# ends. See docs/plans/2026-10-17-vault-continuation-ownership.md for the state shape.
+
+#: ``waiter.liveness`` for a waiter whose owner holds its lock at ``request_waiter_lock_path``.
+WAITER_LIVENESS_LOCK = "lock"
+_WAITER_ID_PATTERN = re.compile(r"vw_[0-9a-f]{12}")
+
+
+class ContinuationClaimedError(InvalidRequestError):
+ """The request's continuation already belongs to someone else; the caller must not deliver."""
+
+
+def new_request_waiter_id() -> str:
+ return _id("vw")
+
+
+def request_waiter_lock_path(db_path: str | Path, waiter_id: str) -> Path:
+ """The waiter's ownership lock, beside the database whose request it waits on."""
+
+ if not _WAITER_ID_PATTERN.fullmatch(str(waiter_id or "")):
+ raise InvalidRequestError("invalid request waiter id")
+ return Path(db_path).expanduser().resolve().parent / "vault-waiters" / f"{waiter_id}.lock"
+
+
+def _database_file(connectable: Any) -> Path | None:
+ database = connectable.engine.url.database
+ if not database or database == ":memory:" or str(database).startswith("file:"):
+ return None
+ return Path(database)
+
+
+def acquire_request_waiter_lock(engine: Any, waiter_id: str) -> MigrationFileLock:
+ """Take a new waiter's ownership lock; raises ``OSError`` when it cannot be held."""
+
+ db_path = _database_file(engine)
+ if db_path is None:
+ raise OSError("the vault database has no file to anchor a waiter lock beside")
+ lock = MigrationFileLock(request_waiter_lock_path(db_path, waiter_id), timeout_seconds=0)
+ lock.acquire()
+ return lock
+
+
+def release_request_waiter_lock(lock: MigrationFileLock, *, discard: bool) -> None:
+ """Release a waiter's lock; ``discard`` once the waiter is terminal in the database.
+
+ A waiter that leaves without a terminal commit must not discard: its row still says
+ ``active``, and only a lock that can now be taken tells the daemon its owner is gone.
+ """
+
+ try:
+ if discard:
+ try:
+ lock.lock_path.unlink()
+ except OSError:
+ pass
+ finally:
+ lock.release()
+
+
+def discard_request_waiter_lock(connectable: Any, waiter_id: str) -> bool:
+ """Remove a terminal waiter's lock file if no live process holds it."""
+
+ db_path = _database_file(connectable)
+ if db_path is None:
+ return False
+ try:
+ path = request_waiter_lock_path(db_path, waiter_id)
+ except InvalidRequestError:
+ return False
+ return remove_unheld_lock(path)
+
+
+def _waiter_lock_state(conn: Connection | None, waiter: dict[str, Any]) -> LockHolderState:
+ db_path = _database_file(conn) if conn is not None else None
+ if db_path is None:
+ return "unknown"
+ try:
+ path = request_waiter_lock_path(db_path, str(waiter.get("id") or ""))
+ except InvalidRequestError:
+ return "unknown"
+ return probe_lock_holder(path)
+
+
+def _waiter_presumed_live(conn: Connection | None, waiter: dict[str, Any]) -> bool:
+ """Whether an armed waiter must still be treated as owning its request's continuation.
+
+ A lock waiter is live while its lock is held and gone once the lock is free. A missing
+ lock or a failed look proves nothing, so the waiter keeps its own declared wait bound.
+ A waiter without ``liveness`` is a released row shape and keeps its recorded deadline.
+ """
+
if waiter.get("status") != "active":
return False
deadline = _parse_iso_datetime(waiter.get("deadline_at"))
- return deadline is not None and deadline > datetime.now(timezone.utc)
+ within_declared_wait = deadline is not None and deadline > datetime.now(timezone.utc)
+ if waiter.get("liveness") != WAITER_LIVENESS_LOCK:
+ return within_declared_wait
+ state = _waiter_lock_state(conn, waiter)
+ if state == "held":
+ return True
+ if state == "free":
+ return False
+ return within_declared_wait
-def _grant_owner_waiter_active(conn: Connection, grants: list[dict[str, Any]]) -> bool:
+def _request_waiter_live(conn: Connection | None, row: dict[str, Any]) -> bool:
+ _, delivery = _request_json_payloads(row)
+ return _waiter_presumed_live(conn, _request_waiter(delivery))
+
+
+def _grant_owner_waiter_live(conn: Connection, grants: list[dict[str, Any]]) -> bool:
request_ids = [
str(grant.get("request_id") or "")
for grant in grants
@@ -1471,7 +1581,12 @@ def _grant_owner_waiter_active(conn: Connection, grants: list[dict[str, Any]]) -
if not request_ids:
return False
rows = conn.execute(select(vault_requests).where(vault_requests.c.id.in_(request_ids))).mappings()
- return any(_request_waiter_active(dict(row)) for row in rows)
+ return any(_request_waiter_live(conn, dict(row)) for row in rows)
+
+
+def _request_continuation_claimed(delivery: dict[str, Any]) -> bool:
+ continuation = delivery.get("continuation")
+ return isinstance(continuation, dict) and continuation.get("owner") == "callback"
def _skip_sibling_callbacks_for_completed_waiter(conn: Connection, request_id: str) -> None:
@@ -1498,6 +1613,10 @@ def _skip_sibling_callbacks_for_completed_waiter(conn: Connection, request_id: s
).mappings()
for row in rows:
row_dict = dict(row)
+ _, sibling_delivery = _request_json_payloads(row_dict)
+ if isinstance(sibling_delivery, dict) and _request_continuation_claimed(sibling_delivery):
+ # Its callback already owns its continuation; skipping now would drop that turn.
+ continue
try:
option = _request_grant_option(row_dict)
except InvalidRequestError:
@@ -1516,78 +1635,108 @@ def _skip_sibling_callbacks_for_completed_waiter(conn: Connection, request_id: s
)
-def _update_request_waiter(
- conn: Connection,
- request_id: str,
- *,
- waiter_id: str,
- status: str,
- deadline_at: str | None = None,
- completed_at: str | None = None,
- timed_out_at: str | None = None,
-) -> dict[str, Any]:
+def _reserve_request_row(conn: Connection, request_id: str) -> tuple[dict[str, Any], dict[str, Any]]:
+ """Take SQLite's write lock, then read the request this transaction will decide on."""
+
+ from storage.agent_session_rows import reserve_write_lock
+
+ reserve_write_lock(conn)
row = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().first()
if row is None:
raise RequestNotFoundError(request_id)
row_dict = dict(row)
_, delivery = _request_json_payloads(row_dict)
- delivery_payload = dict(delivery) if isinstance(delivery, dict) else {}
- current = _request_waiter(delivery_payload)
- if current and current.get("id") and current.get("id") != waiter_id:
- raise InvalidRequestError("request waiter id does not match")
- waiter = {
- "id": waiter_id,
- "status": status,
- "updated_at": _now(),
- }
- if deadline_at:
- waiter["deadline_at"] = deadline_at
- elif current.get("deadline_at"):
- waiter["deadline_at"] = current["deadline_at"]
- if completed_at:
- waiter["completed_at"] = completed_at
- if timed_out_at:
- waiter["timed_out_at"] = timed_out_at
- delivery_payload["waiter"] = waiter
+ return row_dict, dict(delivery) if isinstance(delivery, dict) else {}
- conn.execute(
+
+def _land_request_delivery(conn: Connection, row: dict[str, Any], delivery: dict[str, Any], *conditions: Any) -> bool:
+ """Write ``delivery`` only over the text this decision read; True when it landed."""
+
+ read = row.get("delivery")
+ unchanged = vault_requests.c.delivery.is_(None) if read is None else vault_requests.c.delivery == read
+ result = conn.execute(
vault_requests.update()
- .where(vault_requests.c.id == request_id)
- .values(delivery=json.dumps(delivery_payload))
+ .where(vault_requests.c.id == row["id"], unchanged, *conditions)
+ .values(delivery=json.dumps(delivery))
)
- if status == "completed":
- _skip_sibling_callbacks_for_completed_waiter(conn, request_id)
+ return result.rowcount == 1
+
+
+def _callback_not_sent() -> Any:
+ # A released daemon records a delivered callback only as ``sent``; never continue past it.
+ return or_(vault_requests.c.callback_status.is_(None), vault_requests.c.callback_status != "sent")
+
+
+def _transition_own_waiter(
+ conn: Connection,
+ request_id: str,
+ *,
+ waiter_id: str,
+ status: str,
+ stamp: str,
+ exclusive: bool,
+) -> dict[str, Any]:
+ row, delivery = _reserve_request_row(conn, request_id)
+ current = _request_waiter(delivery)
+ if current.get("id") != waiter_id:
+ raise InvalidRequestError("request waiter id does not match")
+ if current.get("status") != "active" or (
+ exclusive and (_request_continuation_claimed(delivery) or row.get("callback_status") == "sent")
+ ):
+ raise ContinuationClaimedError(f"vault request {request_id} continues through its callback")
+ now = _now()
+ delivery["waiter"] = {**current, "status": status, "updated_at": now, stamp: now}
+ conditions = (_callback_not_sent(),) if exclusive else ()
+ if not _land_request_delivery(conn, row, delivery, *conditions):
+ raise ContinuationClaimedError(f"vault request {request_id} continues through its callback")
updated = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()
return _request_row_payload(dict(updated), conn=conn, audience=REQUEST_AUDIENCE_AGENT)
-def arm_request_waiter(conn: Connection, request_id: str, *, waiter_id: str, deadline_at: str) -> dict[str, Any]:
- return _update_request_waiter(
- conn,
- request_id,
- waiter_id=waiter_id,
- status="active",
- deadline_at=deadline_at,
- )
+def arm_request_waiter(
+ conn: Connection,
+ request_id: str,
+ *,
+ waiter_id: str,
+ deadline_at: str,
+ liveness: str | None = None,
+) -> dict[str, Any]:
+ """Make a synchronous CLI waiter the request's continuation owner.
+
+ Raises ``ContinuationClaimedError`` once the callback owns the request (the caller must
+ not wait or deliver) and ``InvalidRequestError`` when the request already has a waiter.
+ """
+
+ row, delivery = _reserve_request_row(conn, request_id)
+ if _request_waiter(delivery):
+ raise InvalidRequestError("request waiter id does not match")
+ if _request_continuation_claimed(delivery) or row.get("callback_status") == "sent":
+ raise ContinuationClaimedError(f"vault request {request_id} continues through its callback")
+ waiter = {"id": waiter_id, "status": "active", "deadline_at": deadline_at, "updated_at": _now()}
+ if liveness:
+ waiter["liveness"] = liveness
+ delivery["waiter"] = waiter
+ if not _land_request_delivery(conn, row, delivery, _callback_not_sent()):
+ raise ContinuationClaimedError(f"vault request {request_id} continues through its callback")
+ updated = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()
+ return _request_row_payload(dict(updated), conn=conn, audience=REQUEST_AUDIENCE_AGENT)
def complete_request_waiter(conn: Connection, request_id: str, *, waiter_id: str) -> dict[str, Any]:
- return _update_request_waiter(
- conn,
- request_id,
- waiter_id=waiter_id,
- status="completed",
- completed_at=_now(),
+ """Consume the request's outcome in the waiting command; only then may it deliver."""
+
+ payload = _transition_own_waiter(
+ conn, request_id, waiter_id=waiter_id, status="completed", stamp="completed_at", exclusive=True
)
+ _skip_sibling_callbacks_for_completed_waiter(conn, request_id)
+ return payload
def timeout_request_waiter(conn: Connection, request_id: str, *, waiter_id: str) -> dict[str, Any]:
- return _update_request_waiter(
- conn,
- request_id,
- waiter_id=waiter_id,
- status="timed_out",
- timed_out_at=_now(),
+ """Hand an unconsumed request back to its callback when the waiter stops waiting."""
+
+ return _transition_own_waiter(
+ conn, request_id, waiter_id=waiter_id, status="timed_out", stamp="timed_out_at", exclusive=False
)
@@ -1684,11 +1833,12 @@ def _payload_session_id(payload: Any) -> str | None:
# --- Auto-resume callbacks (P4) -------------------------------------------------------------
#
# When a request reaches a terminal state its transition also sets ``callback_status="pending"``.
-# The daemon sweep (``core.scheduled_tasks``) drains these: for each it resolves a callback plan
-# and enqueues exactly one callback turn to the requesting session — the same entry Agent Run /
-# watch / scheduled tasks use — then marks the row ``sent`` / ``skipped``. The atomic
-# ``WHERE status='pending'`` claim on every transition makes this exactly-once (a re-resolve
-# updates zero rows, so ``callback_status`` is never re-armed).
+# The daemon sweep (``core.scheduled_tasks``) drains these: ``claim_request_callback`` decides on
+# the current row whether a synchronous waiter or the callback owns the continuation, the sweep
+# enqueues one callback turn to the requesting session — the same entry Agent Run / watch /
+# scheduled tasks use — or mirrors a waiter-consumed outcome, then marks the row ``sent`` /
+# ``skipped``. The atomic ``WHERE status='pending'`` claim on every transition keeps a re-resolve
+# from re-arming ``callback_status``.
@dataclass(frozen=True)
@@ -1837,12 +1987,13 @@ def request_callback_ready(conn: Connection, row: dict[str, Any]) -> bool:
the active grant for the request's session/purpose whose member snapshot covers the request's
members. Every other terminal state (provision/sign/deny/expire, and standard grants which are
ready on approval) is deliverable immediately; no active covering grant does not block forever.
+ A live synchronous waiter, on this request or on the covering grant's request, also defers it.
"""
- if _request_waiter_active(row):
+ if _request_waiter_live(conn, row):
return False
if str(row.get("request_type") or "") == "access" and str(row.get("status") or "") == "approved":
grants = _request_covering_grant_payloads(conn, row)
- if grants and _grant_owner_waiter_active(conn, grants):
+ if grants and _grant_owner_waiter_live(conn, grants):
return False
if grants and not any(grant.get("delivery_ready") for grant in grants):
return False
@@ -1902,29 +2053,94 @@ def list_pending_request_callbacks(
query = query.limit(limit)
rows = [dict(row) for row in conn.execute(query).mappings()]
for row in rows:
- if row.get("request_type") != "provision" or row.get("status") != "fulfilled":
- continue
- # Transient callback projection: use the user's actual current fields,
- # never the requested hints and never any envelope/value material.
- secret = conn.execute(
- select(vault_secrets.c.name, vault_secrets.c.kind, vault_secrets.c.id,
- vault_secrets.c.public_meta, vault_secrets.c.fields, vault_secrets.c.updated_at)
- .where(vault_secrets.c.name == row.get("secret_name"))
- ).mappings().first()
- if secret is not None:
- current = _field_metadata(dict(secret))
- if has_named_field_shape(current):
- row["provision_secret"] = current
+ _attach_provision_projection(conn, row)
return rows
-def mark_request_callback(conn: Connection, request_id: str, *, status: str) -> None:
- """Record the outcome of an auto-resume callback (``sent`` / ``skipped`` / ``failed``)."""
- conn.execute(
+def _attach_provision_projection(conn: Connection, row: dict[str, Any]) -> None:
+ if row.get("request_type") != "provision" or row.get("status") != "fulfilled":
+ return
+ # Transient callback projection: use the user's actual current fields,
+ # never the requested hints and never any envelope/value material.
+ secret = conn.execute(
+ select(vault_secrets.c.name, vault_secrets.c.kind, vault_secrets.c.id,
+ vault_secrets.c.public_meta, vault_secrets.c.fields, vault_secrets.c.updated_at)
+ .where(vault_secrets.c.name == row.get("secret_name"))
+ ).mappings().first()
+ if secret is not None:
+ current = _field_metadata(dict(secret))
+ if has_named_field_shape(current):
+ row["provision_secret"] = current
+
+
+@dataclass(frozen=True)
+class RequestCallbackClaim:
+ """What one callback pass may do for a request, decided on its current row.
+
+ ``defer`` leaves it for a later pass, ``settled`` means it needs nothing more, ``mirror``
+ records a waiter-consumed outcome in the transcript, and ``deliver`` enqueues the callback
+ Run ``run_id``. ``released_waiter_id`` names a dead owner's lock that is now safe to remove.
+ """
+
+ action: str
+ row: dict[str, Any] | None = None
+ plan: PendingRequestCallback | None = None
+ run_id: str | None = None
+ released_waiter_id: str | None = None
+
+
+def claim_request_callback(conn: Connection, request_id: str) -> RequestCallbackClaim:
+ """Decide, on the current row, whether the Session callback owns this request's continuation.
+
+ The callback claims the request before anything is enqueued, recording the Run id it will
+ use, so a waiter arriving later is refused and a pass interrupted between enqueue and the
+ ``sent`` mark resumes with the same Run instead of choosing again.
+ """
+
+ try:
+ row, delivery = _reserve_request_row(conn, request_id)
+ except RequestNotFoundError:
+ return RequestCallbackClaim("settled")
+ if row.get("callback_status") != "pending":
+ return RequestCallbackClaim("settled", row)
+ _attach_provision_projection(conn, row)
+ plan = resolve_request_callback(row)
+ if plan is None:
+ mark_request_callback(conn, request_id, status="skipped")
+ return RequestCallbackClaim("settled", row)
+ if _request_continuation_claimed(delivery):
+ run_id = str(delivery["continuation"].get("run_id") or "") or None
+ return RequestCallbackClaim("deliver", row, plan, run_id=run_id)
+ if request_callback_consumed_by_waiter(row):
+ return RequestCallbackClaim("mirror", row, plan)
+ if not request_callback_ready(conn, row):
+ return RequestCallbackClaim("defer", row)
+ waiter = _request_waiter(delivery)
+ waiter_armed = waiter.get("status") == "active"
+ now = _now()
+ if waiter_armed:
+ # Gone, or past its declared wait with no proof either way: abandoning it in this same
+ # write is what refuses that waiter's completion.
+ delivery["waiter"] = {**waiter, "status": "abandoned", "updated_at": now, "abandoned_at": now}
+ run_id = uuid.uuid4().hex[:12]
+ delivery["continuation"] = {"owner": "callback", "run_id": run_id, "claimed_at": now}
+ if not _land_request_delivery(conn, row, delivery, vault_requests.c.callback_status == "pending"):
+ return RequestCallbackClaim("defer", row)
+ released = str(waiter.get("id") or "") if waiter_armed and waiter.get("liveness") == WAITER_LIVENESS_LOCK else None
+ return RequestCallbackClaim("deliver", row, plan, run_id=run_id, released_waiter_id=released or None)
+
+
+def mark_request_callback(conn: Connection, request_id: str, *, status: str) -> bool:
+ """Record the outcome of an owed auto-resume callback (``sent`` / ``skipped`` / ``failed``).
+
+ Only a still-pending callback is marked, so a skip decided elsewhere is never overwritten.
+ """
+ result = conn.execute(
vault_requests.update()
- .where(vault_requests.c.id == request_id)
+ .where(vault_requests.c.id == request_id, vault_requests.c.callback_status == "pending")
.values(callback_status=status)
)
+ return result.rowcount == 1
def _request_card(row: dict[str, Any]) -> dict[str, Any]:
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 4f2c44228..417ab7276 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -633,6 +633,45 @@ def test_task_execution_store_uses_sqlite_runs_when_root_is_default(tmp_path: Pa
assert saved["session_key"] == "slack::channel::C123"
[email protected]("backend", ["sqlite", "file"])
+def test_caller_fixed_run_id_cannot_requeue_a_run_inserted_after_the_initial_lookup(tmp_path, monkeypatch, backend):
+ """A second callback pass must not overwrite the first pass's already-settled Run.
+
+ Sequential recovery covered only an existing initial lookup. Here the lookup
+ sees no row, then another producer enqueues and completes before it returns.
+ Both stores must arbitrate at the write, not trust that stale absence.
+ """
+ store = TaskExecutionStore() if backend == "sqlite" else TaskExecutionStore(tmp_path / "fixed-runs")
+ arguments = {
+ "message": "Resume the approved task once",
+ "source_kind": "callback",
+ "source_actor": "vault:vrq_test",
+ "agent_backend": "vibey",
+ "run_id": "012345abcdef",
+ }
+ real_get = store.get_run
+ raced = False
+
+ def lookup_then_competing_completion(run_id):
+ nonlocal raced
+ snapshot = real_get(run_id)
+ if not raced:
+ raced = True
+ winner = store.enqueue_agent_run(**arguments)
+ claimed = store.claim(winner.id)
+ assert claimed is not None
+ store.complete(claimed, ok=True)
+ assert real_get(run_id)["status"] == "succeeded"
+ return snapshot
+
+ monkeypatch.setattr(store, "get_run", lookup_then_competing_completion)
+ replay = store.enqueue_agent_run(**arguments)
+
+ assert replay.id == arguments["run_id"]
+ assert real_get(replay.id)["status"] == "succeeded"
+ assert store.list_pending() == []
+
+
def test_sqlite_complete_persists_resolved_run_target(tmp_path: Path) -> None:
sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
store = TaskExecutionStore(tmp_path / "task_requests")
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index 6189f6397..3b63ec62b 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -10,6 +10,7 @@ import io
import json
import shlex
import shutil
+import sys
import threading
import time
from pathlib import Path
@@ -1542,7 +1543,96 @@ def test_run_waits_for_protected_approval_then_delivers(tmp_path, capfd, monkeyp
with cli._open_vault_engine().connect() as conn:
row = conn.execute(vault_requests.select().where(vault_requests.c.id == approved["request"]["id"])).mappings().one()
assert row["callback_status"] == "pending"
- assert json.loads(row["delivery"])["waiter"]["status"] == "completed"
+ waiter = json.loads(row["delivery"])["waiter"]
+ assert waiter["status"] == "completed"
+ assert waiter["liveness"] == vault_service.WAITER_LIVENESS_LOCK
+ lock_path = vault_service.request_waiter_lock_path(cli._open_vault_engine().url.database, waiter["id"])
+ assert not lock_path.exists() or sys.platform == "win32"
+
+
[email protected]("operation", ["run", "fetch"])
[email protected]("lose_at", ["arm", "complete"])
+def test_waiter_that_loses_the_approval_to_its_callback_does_not_deliver(tmp_path, capfd, monkeypatch, operation, lose_at):
+ from vibe import api
+
+ monkeypatch.chdir(tmp_path)
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="PROTECTED_KEY",
+ protection="protected",
+ sealed=_sealed("protected"),
+ policy={"allowed_hosts": ["api.example.com"]},
+ )
+
+ def callback_claims(request_id: str) -> None:
+ with cli._open_vault_engine().begin() as conn:
+ if lose_at == "arm":
+ request = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_AGENT)
+ _grant_from_request(conn, request, session_id="ses_cli")
+ claim = vault_service.claim_request_callback(conn, request_id)
+ assert claim.action == "deliver"
+
+ approver = None
+ if lose_at == "arm":
+ # Approval and a daemon pass land between the request's creation and the waiter's arm.
+ real_arm = vault_service.arm_request_waiter
+
+ def arm_after_claim(conn, request_id, **kwargs):
+ callback_claims(request_id)
+ return real_arm(conn, request_id, **kwargs)
+
+ monkeypatch.setattr(vault_service, "arm_request_waiter", arm_after_claim)
+ else:
+ # A wrong death verdict lets the callback take over a waiter that is about to complete.
+ real_complete = vault_service.complete_request_waiter
+
+ def complete_after_takeover(conn, request_id, **kwargs):
+ with monkeypatch.context() as misjudged:
+ misjudged.setattr(vault_service, "_waiter_lock_state", lambda *_: "free")
+ callback_claims(request_id)
+ return real_complete(conn, request_id, **kwargs)
+
+ monkeypatch.setattr(vault_service, "complete_request_waiter", complete_after_takeover)
+ approver = threading.Thread(target=_approve_next_pending_access_request, kwargs={"session_id": "ses_cli", "purpose": operation})
+ approver.start()
+ deliver = Mock(return_value={"exit_code": 0, "status": 200, "headers": {}, "body": "{}"})
+ for name in ("avault_agent_deliver_run", "avault_deliver_run", "avault_agent_deliver_fetch", "avault_deliver_fetch"):
+ monkeypatch.setattr(api, name, deliver)
+
+ if operation == "run":
+ code = cli.cmd_vault_run(
+ _ns(env=["PROTECTED_KEY"], command_argv=["python3", "-c", "pass"], session_id="ses_cli", approval_wait=APPROVAL_POLL_TIMEOUT)
+ )
+ else:
+ code = cli.cmd_vault_fetch(
+ _ns(
+ auth="PROTECTED_KEY",
+ url="https://api.example.com/v1",
+ method="GET",
+ header=None,
+ data=None,
+ data_file=None,
+ output=None,
+ group=None,
+ session_id="ses_cli",
+ approval_wait=APPROVAL_POLL_TIMEOUT,
+ )
+ )
+ if approver is not None:
+ approver.join(timeout=APPROVAL_POLL_TIMEOUT)
+ assert not approver.is_alive()
+ captured = capfd.readouterr()
+ payload = json.loads(captured.err[captured.err.index("{") :])
+
+ assert code == 1
+ assert payload["code"] == "approval_handed_off"
+ deliver.assert_not_called()
+ with cli._open_vault_engine().connect() as conn:
+ row = conn.execute(vault_requests.select().where(vault_requests.c.id == payload["details"]["request_id"])).mappings().one()
+ delivery = json.loads(row["delivery"])
+ assert delivery["continuation"]["owner"] == "callback"
+ assert delivery.get("waiter", {}).get("status") in (None, "abandoned")
def test_run_approval_wait_timeout_keeps_callback_armed_for_later_resolution(capfd):
diff --git a/tests/test_vault_request_callbacks.py b/tests/test_vault_request_callbacks.py
index b6a36132e..1b5182b80 100644
--- a/tests/test_vault_request_callbacks.py
+++ b/tests/test_vault_request_callbacks.py
@@ -8,7 +8,12 @@ a synchronous CLI waiter already returned the result, then marks the callback se
from __future__ import annotations
import json
+import os
+import subprocess
+import sys
+import time
from datetime import datetime, timedelta, timezone
+from pathlib import Path
import pytest
from sqlalchemy import select
@@ -149,6 +154,10 @@ def test_field_provision_callback_reports_current_value_free_fields(vault, with_
assert "totp" not in plan.message and "password" not in plan.message
assert "do-not-show" not in plan.message
assert "ciphertext" not in plan.message
+ # The callback decides on the current row and must keep the same current-field projection.
+ claim = vs.claim_request_callback(conn, req["id"])
+ assert claim.action == "deliver"
+ assert claim.plan.message == plan.message
@pytest.mark.parametrize(
@@ -830,3 +839,326 @@ def test_legacy_callback_drain_mirrors_completed_waiter_without_second_agent_tur
only_session="ses_vault_waiter",
)
assert inbox["sessions"][0]["replied"] is True
+
+
+# --- continuation ownership: a synchronous CLI waiter versus the Session callback -------------
+
+
+_REPO_ROOT = Path(__file__).resolve().parents[1]
+
+
+def _start_waiting_vault_run(session_id: str, *, approval_wait: int = 540):
+ """A real ``vibe vault run`` that blocks on protected approval, in this test's home."""
+
+ env = dict(os.environ)
+ env["AVIBE_SESSION_ID"] = session_id
+ env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(_REPO_ROOT), env.get("PYTHONPATH", "")]))
+ argv = [
+ "vault", "run", "--env", "PROTECTED_KEY", "--approval-wait", str(approval_wait),
+ "--", sys.executable, "-c", "pass",
+ ]
+ return subprocess.Popen(
+ [sys.executable, "-c", "import sys; from vibe import cli; sys.argv = ['vibe', *sys.argv[1:]]; cli.main()", *argv],
+ cwd=str(_REPO_ROOT),
+ env=env,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+
+def _wait_for_active_waiter(engine, proc) -> dict:
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ assert proc.poll() is None, "the waiting vault run exited before arming its waiter"
+ with engine.connect() as conn:
+ for row in conn.execute(select(vault_requests).where(vault_requests.c.request_type == "access")).mappings():
+ waiter = (json.loads(row["delivery"] or "{}") or {}).get("waiter") or {}
+ if waiter.get("status") == "active":
+ return dict(row)
+ time.sleep(0.05)
+ raise AssertionError("the vault run never armed an approval waiter")
+
+
+def _callback_service(monkeypatch, tmp_path, *, backend="file"):
+ from types import SimpleNamespace
+
+ from core import scheduled_tasks as st
+
+ class _Key:
+ def to_key(self) -> str:
+ return "avibe::scope::ses_owner"
+
+ target = SimpleNamespace(
+ session_key=_Key(),
+ agent_name="vibey",
+ agent_id="aid",
+ agent_backend="vibey",
+ model=None,
+ reasoning_effort=None,
+ )
+ monkeypatch.setattr(st, "resolve_session_id_target", lambda session_id: target)
+ request_store = st.TaskExecutionStore() if backend == "sqlite" else st.TaskExecutionStore(tmp_path / "task_requests")
+
+ def service():
+ # A fresh instance per call is a service restart: no in-memory owner state survives it.
+ return st.ScheduledTaskService(
+ controller=SimpleNamespace(platform_settings_managers={}),
+ store=st.ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ return service, request_store
+
+
+def test_hard_killed_waiter_hands_a_ready_approval_to_the_callback_before_its_deadline(monkeypatch, tmp_path):
+ from vibe import cli
+
+ engine = cli._open_vault_engine()
+ with engine.begin() as conn:
+ vs.create_secret(conn, name="PROTECTED_KEY", sealed=_sealed("kill"), protection="protected")
+ proc = _start_waiting_vault_run("ses_owner")
+ try:
+ armed = _wait_for_active_waiter(engine, proc)
+ finally:
+ proc.kill()
+ proc.wait(timeout=30)
+ waiter = json.loads(armed["delivery"])["waiter"]
+ assert datetime.fromisoformat(waiter["deadline_at"]) > datetime.now(timezone.utc) + timedelta(minutes=5)
+
+ with engine.begin() as conn:
+ request = vs.get_request(conn, armed["id"], audience=vs.REQUEST_AUDIENCE_AGENT)
+ _grant_from_request(conn, request)
+ row = _row(conn, armed["id"])
+ service, request_store = _callback_service(monkeypatch, tmp_path)
+
+ assert service()._process_vault_callback_sync(row) == "sent"
+
+ [callback_run] = request_store.list_pending()
+ assert callback_run.session_id == "ses_owner"
+ assert callback_run.source_actor == f"vault:{armed['id']}"
+ with engine.connect() as conn:
+ delivery = json.loads(_row(conn, armed["id"])["delivery"])
+ assert _callback_status(conn, armed["id"]) == "sent"
+ assert delivery["waiter"]["status"] == "abandoned"
+ assert delivery["continuation"]["run_id"] == callback_run.id
+
+
+def _arm_lock_waiter(engine, request_id: str, *, deadline_at: str | None = None):
+ """Arm a lock-evidenced waiter the way ``vibe vault run`` does; returns its held lock."""
+
+ waiter_id = vs.new_request_waiter_id()
+ lock = vs.acquire_request_waiter_lock(engine, waiter_id)
+ with engine.begin() as conn:
+ vs.arm_request_waiter(
+ conn,
+ request_id,
+ waiter_id=waiter_id,
+ deadline_at=deadline_at or (datetime.now(timezone.utc) + timedelta(minutes=9)).isoformat(),
+ liveness=vs.WAITER_LIVENESS_LOCK,
+ )
+ return waiter_id, lock
+
+
+def _owner_request(conn, name: str, session_id: str = "ses_owner", **kwargs) -> dict:
+ vs.create_secret(conn, name=name, sealed=_sealed(name.lower()), protection="protected", **kwargs)
+ return vs.create_access_request(conn, name, requester={"session_id": session_id}, delivery={"session_id": session_id})
+
+
+def _record_mirrors(monkeypatch) -> list[dict]:
+ mirrored: list[dict] = []
+
+ def mirror(**kwargs):
+ mirrored.append(kwargs)
+ return True
+
+ monkeypatch.setattr("core.message_mirror.mirror_vault_waiter_outcome", mirror)
+ return mirrored
+
+
+def test_live_waiter_keeps_its_approval_past_its_wall_clock_deadline_and_across_restart(monkeypatch, tmp_path):
+ from config import paths
+ from vibe import cli
+
+ engine = cli._open_vault_engine()
+ with engine.begin() as conn:
+ req = _owner_request(conn, "LIVE_KEY")
+ # A suspended machine or a stepped clock: the recorded deadline passed while the owner still waits.
+ past = (datetime.now(timezone.utc) - timedelta(minutes=1)).isoformat()
+ waiter_id, lock = _arm_lock_waiter(engine, req["id"], deadline_at=past)
+ service, request_store = _callback_service(monkeypatch, tmp_path)
+ mirrored = _record_mirrors(monkeypatch)
+ try:
+ with engine.begin() as conn:
+ _grant_from_request(conn, req)
+ row = _row(conn, req["id"])
+ assert service()._process_vault_callback_sync(row) == "pending"
+ assert service()._process_vault_callback_sync(row) == "pending"
+ with engine.begin() as conn:
+ vs.complete_request_waiter(conn, req["id"], waiter_id=waiter_id)
+ finally:
+ vs.release_request_waiter_lock(lock, discard=True)
+
+ assert service()._process_vault_callback_sync(row) == "sent"
+ assert request_store.list_pending() == []
+ assert [entry["request_id"] for entry in mirrored] == [req["id"]]
+ with engine.connect() as conn:
+ delivery = json.loads(_row(conn, req["id"])["delivery"])
+ assert delivery["waiter"]["status"] == "completed"
+ assert "continuation" not in delivery
+ assert vs.probe_lock_holder(vs.request_waiter_lock_path(paths.get_sqlite_state_path(), waiter_id)) in {"free", "missing"}
+
+
[email protected]("backend", ["sqlite", "file"])
+def test_claimed_callback_survives_enqueue_before_mark_and_refuses_a_later_waiter(monkeypatch, tmp_path, backend):
+ from vibe import cli
+
+ engine = cli._open_vault_engine()
+ with engine.begin() as conn:
+ req = _owner_request(conn, "CLAIM_KEY")
+ _grant_from_request(conn, req)
+ row = _row(conn, req["id"])
+ service, request_store = _callback_service(monkeypatch, tmp_path, backend=backend)
+
+ def stopped_before_mark(conn, request_id, *, status):
+ raise RuntimeError("the daemon stopped between enqueue and the sent mark")
+
+ with monkeypatch.context() as interrupted:
+ interrupted.setattr(vs, "mark_request_callback", stopped_before_mark)
+ assert service()._process_vault_callback_sync(row) == "pending"
+ [callback_run] = request_store.list_pending()
+
+ # The restarted daemon resumes the claim it recorded instead of deciding (and enqueueing) again.
+ assert service()._process_vault_callback_sync(row) == "sent"
+ assert [run.id for run in request_store.list_pending()] == [callback_run.id]
+ with engine.begin() as conn:
+ assert json.loads(_row(conn, req["id"])["delivery"])["continuation"]["run_id"] == callback_run.id
+ # A command that only now reaches its waiter must not also continue this approval.
+ with pytest.raises(vs.ContinuationClaimedError):
+ vs.arm_request_waiter(
+ conn,
+ req["id"],
+ waiter_id=vs.new_request_waiter_id(),
+ deadline_at=(datetime.now(timezone.utc) + timedelta(minutes=9)).isoformat(),
+ liveness=vs.WAITER_LIVENESS_LOCK,
+ )
+
+
[email protected]("case", ["waiter_completed", "sibling_skipped"])
+def test_stale_scan_row_cannot_start_a_second_continuation(monkeypatch, tmp_path, case):
+ from vibe import cli
+
+ engine = cli._open_vault_engine()
+ service, request_store = _callback_service(monkeypatch, tmp_path)
+ mirrored = _record_mirrors(monkeypatch)
+ with engine.begin() as conn:
+ primary = _owner_request(conn, "STALE_A", tags=["deploy"])
+ sibling = vs.create_access_request(
+ conn, "STALE_A", requester={"session_id": "ses_owner"}, delivery={"session_id": "ses_owner"}
+ )
+ deadline_at = (datetime.now(timezone.utc) + timedelta(minutes=9)).isoformat()
+ if case == "waiter_completed":
+ # The scan sees an approved request with no waiter; the command arms and consumes it after.
+ with engine.begin() as conn:
+ _grant_from_request(conn, primary)
+ stale = _row(conn, primary["id"])
+ vs.arm_request_waiter(conn, primary["id"], waiter_id="vw_00000000000a", deadline_at=deadline_at)
+ processed = primary["id"]
+ else:
+ with engine.begin() as conn:
+ vs.arm_request_waiter(conn, primary["id"], waiter_id="vw_00000000000a", deadline_at=deadline_at)
+ _grant_from_request(conn, primary)
+ stale = _row(conn, sibling["id"])
+ processed = sibling["id"]
+ assert stale["callback_status"] == "pending"
+ with engine.begin() as conn:
+ vs.complete_request_waiter(conn, primary["id"], waiter_id="vw_00000000000a")
+
+ status = service()._process_vault_callback_sync(stale)
+
+ assert request_store.list_pending() == []
+ with engine.connect() as conn:
+ if case == "waiter_completed":
+ assert status == "sent"
+ assert [entry["request_id"] for entry in mirrored] == [processed]
+ else:
+ assert status == "skipped"
+ assert mirrored == []
+ assert _callback_status(conn, processed) == "skipped"
+
+
+ "owner, deadline_minutes, expected",
+ [
+ # Released rows keep their recorded deadline: never presumed dead before it.
+ ("legacy", 9, "defer"),
+ ("legacy", -1, "deliver"),
+ # A lock nobody holds proves the owner is gone, whatever its deadline says.
+ ("lock_released", 9, "deliver"),
+ # A missing lock is not proof of death: the owner keeps its own declared wait bound.
+ ("lock_missing", 9, "defer"),
+ ("lock_missing", -1, "deliver"),
+ ],
+)
+def test_claim_follows_waiter_owner_evidence(vault, owner, deadline_minutes, expected):
+ deadline_at = (datetime.now(timezone.utc) + timedelta(minutes=deadline_minutes)).isoformat()
+ with vault.begin() as conn:
+ req = _owner_request(conn, "EVIDENCE_KEY")
+ if owner == "legacy":
+ with vault.begin() as conn:
+ vs.arm_request_waiter(conn, req["id"], waiter_id="vw_000000000001", deadline_at=deadline_at)
+ else:
+ _, lock = _arm_lock_waiter(vault, req["id"], deadline_at=deadline_at)
+ vs.release_request_waiter_lock(lock, discard=owner == "lock_missing")
+ if owner == "lock_missing":
+ # Windows cannot unlink the held handle; make the missing-evidence fixture
+ # explicit after release rather than accidentally testing a free lock.
+ lock.lock_path.unlink(missing_ok=True)
+ with vault.begin() as conn:
+ _grant_from_request(conn, req)
+ claim = vs.claim_request_callback(conn, req["id"])
+ delivery = json.loads(_row(conn, req["id"])["delivery"])
+
+ assert claim.action == expected
+ if expected == "deliver":
+ assert delivery["waiter"]["status"] == "abandoned"
+ assert delivery["continuation"]["run_id"] == claim.run_id
+ else:
+ assert delivery["waiter"]["status"] == "active"
+ assert "continuation" not in delivery
+
+
+def test_dead_owner_still_waits_for_a_delivery_ready_grant(vault):
+ with vault.begin() as conn:
+ req = _owner_request(conn, "NOT_READY_KEY")
+ waiter_id, lock = _arm_lock_waiter(vault, req["id"])
+ vs.release_request_waiter_lock(lock, discard=False)
+ with vault.begin() as conn:
+ grant = _grant_from_request_with_cache_ready(conn, req, cache_ready=False)
+ assert vs.claim_request_callback(conn, req["id"]).action == "defer"
+ assert "continuation" not in json.loads(_row(conn, req["id"])["delivery"])
+
+ vs.mark_grant_agent_ready(conn, grant["id"])
+ claim = vs.claim_request_callback(conn, req["id"])
+
+ assert claim.action == "deliver"
+ assert claim.released_waiter_id == waiter_id
+
+
[email protected]("owner_live, expected", [(True, "defer"), (False, "deliver")])
+def test_covered_sibling_follows_the_grant_owner_waiter(vault, owner_live, expected):
+ with vault.begin() as conn:
+ primary = _owner_request(conn, "SIB_A", tags=["deploy"])
+ sibling = vs.create_access_request(
+ conn, "SIB_A", requester={"session_id": "ses_owner"}, delivery={"session_id": "ses_owner"}
+ )
+ _, lock = _arm_lock_waiter(vault, primary["id"])
+ try:
+ if not owner_live:
+ vs.release_request_waiter_lock(lock, discard=False)
+ with vault.begin() as conn:
+ _grant_from_request(conn, primary)
+ assert vs.claim_request_callback(conn, sibling["id"]).action == expected
+ finally:
+ if owner_live:
+ vs.release_request_waiter_lock(lock, discard=False)
diff --git a/vibe/cli.py b/vibe/cli.py
index a3834ffee..0fb8ad37a 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -10330,42 +10330,89 @@ def _vault_terminal_request_error(request: dict, *, help_command: str) -> TaskCl
return None
+def _vault_approval_handed_off_error(args, request_id: str, *, help_command: str) -> TaskCliError:
+ return TaskCliError(
+ f"Vault request '{request_id}' continues through its Session callback; this command did not run",
+ code="approval_handed_off",
+ hint=_approval_wait_timeout_hint(args, request_id),
+ help_command=help_command,
+ details={"request_id": request_id, "callback_expected": _approval_wait_callback_expected(args)},
+ )
+
+
def _wait_for_vault_delivery_approval(args, exc: TaskCliError, *, timeout: float, help_command: str, operation: str) -> None:
+ """Wait as the request's continuation owner; return only when this command may deliver.
+
+ The waiter holds an OS lock for as long as it owns the request, so a waiter killed in any
+ way hands a ready approval to the Session callback on the daemon's next pass. Losing the
+ request to that callback, at arm or at completion, means this command must not deliver.
+ """
+
from storage import vault_service
request_id = str((exc.details or {}).get("request_id") or "").strip()
if not request_id:
raise exc
- waiter_id = f"vw_{uuid4().hex[:12]}"
- deadline_at = (datetime.now(timezone.utc) + timedelta(seconds=timeout)).isoformat()
+ waiter_id = vault_service.new_request_waiter_id()
engine = _open_vault_engine()
- with engine.begin() as conn:
- vault_service.arm_request_waiter(conn, request_id, waiter_id=waiter_id, deadline_at=deadline_at)
- _print_vault_approval_wait_notice(request_id, timeout=timeout, operation=operation)
- waited = _wait_for_vault_request(request_id, timeout=timeout, require_delivery_ready=True)
- if waited is None:
+ try:
+ lock = vault_service.acquire_request_waiter_lock(engine, waiter_id)
+ except OSError:
+ # Without proof of life this command cannot own the request; the callback keeps it.
+ logger.debug("failed to take the vault request waiter lock", exc_info=True)
+ raise exc
+ terminal = True
+ try:
+ deadline_at = (datetime.now(timezone.utc) + timedelta(seconds=timeout)).isoformat()
try:
with engine.begin() as conn:
- vault_service.timeout_request_waiter(conn, request_id, waiter_id=waiter_id)
- except Exception:
- logger.debug("failed to mark vault request waiter timed out", exc_info=True)
- raise TaskCliError(
- f"Vault approval request '{request_id}' is still waiting for the user",
- code="approval_wait_timeout",
- hint=_approval_wait_timeout_hint(args, request_id),
- help_command=help_command,
- details={
- "request_id": request_id,
- "timeout_seconds": timeout,
- "callback_expected": _approval_wait_callback_expected(args),
- },
- )
- request = waited.get("request") or {}
- terminal_error = _vault_terminal_request_error(request, help_command=help_command)
- with engine.begin() as conn:
- vault_service.complete_request_waiter(conn, request_id, waiter_id=waiter_id)
- if terminal_error is not None:
- raise terminal_error
+ vault_service.arm_request_waiter(
+ conn,
+ request_id,
+ waiter_id=waiter_id,
+ deadline_at=deadline_at,
+ liveness=vault_service.WAITER_LIVENESS_LOCK,
+ )
+ except vault_service.ContinuationClaimedError:
+ raise _vault_approval_handed_off_error(args, request_id, help_command=help_command)
+ terminal = False
+ _print_vault_approval_wait_notice(request_id, timeout=timeout, operation=operation)
+ waited = _wait_for_vault_request(request_id, timeout=timeout, require_delivery_ready=True)
+ if waited is None:
+ try:
+ with engine.begin() as conn:
+ vault_service.timeout_request_waiter(conn, request_id, waiter_id=waiter_id)
+ terminal = True
+ except vault_service.ContinuationClaimedError:
+ terminal = True
+ except Exception:
+ logger.debug("failed to mark vault request waiter timed out", exc_info=True)
+ raise TaskCliError(
+ f"Vault approval request '{request_id}' is still waiting for the user",
+ code="approval_wait_timeout",
+ hint=_approval_wait_timeout_hint(args, request_id),
+ help_command=help_command,
+ details={
+ "request_id": request_id,
+ "timeout_seconds": timeout,
+ "callback_expected": _approval_wait_callback_expected(args),
+ },
+ )
+ request = waited.get("request") or {}
+ terminal_error = _vault_terminal_request_error(request, help_command=help_command)
+ try:
+ with engine.begin() as conn:
+ vault_service.complete_request_waiter(conn, request_id, waiter_id=waiter_id)
+ except vault_service.ContinuationClaimedError:
+ terminal = True
+ raise _vault_approval_handed_off_error(args, request_id, help_command=help_command)
+ terminal = True
+ if terminal_error is not None:
+ raise terminal_error
+ finally:
+ # Discard only once the database no longer says this waiter is active; otherwise a free
+ # lock is the daemon's only evidence that this owner is gone.
+ vault_service.release_request_waiter_lock(lock, discard=terminal)
def _vault_provision_success_usage(engine, name: str) -> str: