Skip to content

schedule_registry

schedule_registry

Durable recurring-score registrations and exact due-time claims.

The registry is a small projection in the conductor state database. It never executes score sources or calculates recurrence; callers supply validated ScheduleConfig instances and their calculated next epoch due time.

Classes

ScheduleRegistryError

Bases: RuntimeError

Base error for a diagnosable schedule-registry failure.

ScheduleRegistryBusyError

Bases: ScheduleRegistryError

The bounded SQLite wait expired while another writer held the database.

ScheduleRegistryDataError

Bases: ScheduleRegistryError

A persisted schedule row cannot safely be interpreted as registry state.

ScheduleRegistryClaimError

Bases: ScheduleRegistryError

A lifecycle update does not match a durable claimed due identity.

ScheduleRecord dataclass

ScheduleRecord(schedule_id, score_name, score_path, schedule_json, source_digest, enabled, next_due_at, created_at, updated_at, last_due_at, last_run_id, last_outcome, consecutive_drops, pinned_source_digest=None, diagnostic=None, registration_id=None)

Persistent schedule projection visible to the recurrence controller.

DueClaim dataclass

DueClaim(schedule_id, due_at)

The durable identity of a schedule tick claimed by this conductor.

ScheduleRegistry

ScheduleRegistry(db_path, *, busy_timeout_seconds=0.25)

Async SQLite schedule registry with atomic, durable due-time claims.

last_claimed_due_at is intentionally private schema state: it is a durable idempotency key, not schedule status exposed to users. A claim is never released, so reopening the conductor cannot submit the same due time twice.

Source code in src/marianne/daemon/schedule_registry.py
def __init__(self, db_path: Path, *, busy_timeout_seconds: float = 0.25) -> None:
    if not math.isfinite(busy_timeout_seconds) or busy_timeout_seconds <= 0:
        raise ValueError("busy_timeout_seconds must be a positive finite duration")
    self._db_path = db_path
    self._busy_timeout_seconds = busy_timeout_seconds
    self._conn: aiosqlite.Connection | None = None
    self._custody_lock = asyncio.Lock()
    resolved = db_path.resolve()
    # Keep the witness outside the DB's directory so restoring a state
    # directory cannot silently restore its old authority with it.
    custody_name = hashlib.sha256(str(resolved).encode("utf-8")).hexdigest()
    self._custody_path = (
        resolved.parent.parent / ".marianne-venue-custody" / custody_name
    )
Methods:
open async
open()

Open the state database and add the schedules table if necessary.

Source code in src/marianne/daemon/schedule_registry.py
async def open(self) -> None:
    """Open the state database and add the schedules table if necessary."""
    if self._conn is not None:
        return

    await asyncio.to_thread(self._db_path.parent.mkdir, parents=True, exist_ok=True)
    new_database = not self._db_path.exists()
    conn = await aiosqlite.connect(
        str(self._db_path), timeout=self._busy_timeout_seconds
    )
    try:
        conn.row_factory = aiosqlite.Row
        await conn.execute("PRAGMA journal_mode=WAL")
        await conn.execute(
            f"PRAGMA busy_timeout={int(self._busy_timeout_seconds * 1000)}"
        )
        new_identity = await self._create_tables(
            conn, allow_pre_witness_migration=not self._custody_path.exists(),
        )
        if new_identity is not None and (
            new_database or not self._custody_path.exists()
        ):
            await asyncio.to_thread(self._write_custody, new_identity, 0)
    except sqlite3.Error as exc:
        await conn.close()
        self._raise_database_error("open", exc)
    except Exception:
        await conn.close()
        raise
    self._conn = conn
identity async
identity()

Return the identity of this durable state database, across restarts.

Source code in src/marianne/daemon/schedule_registry.py
async def identity(self) -> str:
    """Return the identity of this durable state database, across restarts."""
    async with self._custody_lock:
        identity, _ = await self._checked_identity()
        return identity
upsert async
upsert(schedule_id, score_name, score_path, schedule, source_digest, next_due_at, *, pinned_source_digest=None, registration_id=None)

Insert or replace a schedule declaration without losing its creation time.

pinned_source_digest stores launch-side authority in this daemon-owned row: when set, ticks must refuse byte or identity drift instead of re-binding. Each registration re-derives it from the pinning declaration, so a conscious re-registration amends the pin.

Source code in src/marianne/daemon/schedule_registry.py
async def upsert(
    self,
    schedule_id: str,
    score_name: str,
    score_path: Path,
    schedule: ScheduleConfig,
    source_digest: str,
    next_due_at: float,
    *,
    pinned_source_digest: str | None = None,
    registration_id: str | None = None,
) -> None:
    """Insert or replace a schedule declaration without losing its creation time.

    ``pinned_source_digest`` stores launch-side authority in this
    daemon-owned row: when set, ticks must refuse byte or identity drift
    instead of re-binding. Each registration re-derives it from the
    pinning declaration, so a conscious re-registration amends the pin.
    """
    _require_epoch(next_due_at, name="next_due_at")
    now = time.time()
    await self._execute_mutation(
        "upsert",
        """
        INSERT INTO schedules (
            schedule_id, score_name, score_path, schedule_json,
            source_digest, pinned_source_digest, enabled, next_due_at,
            created_at, updated_at, registration_id
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(schedule_id) DO UPDATE SET
            score_name = excluded.score_name,
            score_path = excluded.score_path,
            schedule_json = excluded.schedule_json,
            source_digest = excluded.source_digest,
            pinned_source_digest = excluded.pinned_source_digest,
            registration_id = excluded.registration_id,
            enabled = excluded.enabled,
            next_due_at = excluded.next_due_at,
            updated_at = excluded.updated_at
        """,
        (
            schedule_id,
            score_name,
            str(score_path),
            schedule.model_dump_json(
                exclude={"max_wall_seconds"}
                if schedule.max_wall_seconds is None else None
            ),
            source_digest,
            pinned_source_digest,
            int(schedule.enabled),
            next_due_at,
            now,
            now,
            registration_id,
        ),
        schedule_id=schedule_id,
    )
terminal_for async
terminal_for(registration_id)

Read a completed cancellation bound to one caller-held registration.

Source code in src/marianne/daemon/schedule_registry.py
async def terminal_for(self, registration_id: str) -> tuple[str, str, str] | None:
    """Read a completed cancellation bound to one caller-held registration."""
    await self.identity()
    try:
        cursor = await self._db.execute(
            "SELECT schedule_id, registry_identity, source_digest FROM schedule_terminals "
            "WHERE registration_id = ?", (registration_id,),
        )
        row = await cursor.fetchone()
    except sqlite3.Error as exc:
        self._raise_database_error("read terminal", exc)
    return (row["schedule_id"], row["registry_identity"], row["source_digest"]) if row else None
record_terminal async
record_terminal(registration_id, schedule_id, source_digest)

Record completed stop only while no later registration owns this ID.

Source code in src/marianne/daemon/schedule_registry.py
async def record_terminal(
    self, registration_id: str, schedule_id: str, source_digest: str,
) -> bool:
    """Record completed stop only while no later registration owns this ID."""
    identity = await self.identity()
    cursor = await self._execute_mutation(
        "record terminal",
        "INSERT OR IGNORE INTO schedule_terminals "
        "(registration_id, schedule_id, registry_identity, source_digest, retired_at) "
        "SELECT ?, ?, ?, ?, ? WHERE NOT EXISTS "
        "(SELECT 1 FROM schedules WHERE schedule_id = ?)",
        (registration_id, schedule_id, identity, source_digest, time.time(), schedule_id),
        schedule_id=schedule_id,
    )
    return cursor.rowcount == 1
get async
get(schedule_id)

Return one durable schedule record, or None when it is absent.

Source code in src/marianne/daemon/schedule_registry.py
async def get(self, schedule_id: str) -> ScheduleRecord | None:
    """Return one durable schedule record, or ``None`` when it is absent."""
    await self.identity()
    try:
        cursor = await self._db.execute(
            "SELECT * FROM schedules WHERE schedule_id = ?", (schedule_id,)
        )
        row = await cursor.fetchone()
    except sqlite3.Error as exc:
        self._raise_database_error("get", exc, schedule_id=schedule_id)
    if row is None:
        return None
    return self._row_to_record(row)
list async
list()

List projections, surfacing malformed rows as safe disabled diagnostics.

Startup restoration must not let one damaged durable projection prevent every other schedule from restoring. get() remains strict for a caller that explicitly requests that row; the bulk view returns one safe disabled diagnostic without deserializing the damaged payload.

Source code in src/marianne/daemon/schedule_registry.py
async def list(self) -> list[ScheduleRecord]:
    """List projections, surfacing malformed rows as safe disabled diagnostics.

    Startup restoration must not let one damaged durable projection prevent
    every other schedule from restoring. ``get()`` remains strict for a
    caller that explicitly requests that row; the bulk view returns one
    safe disabled diagnostic without deserializing the damaged payload.
    """
    await self.identity()
    try:
        cursor = await self._db.execute("SELECT * FROM schedules ORDER BY schedule_id")
        rows = await cursor.fetchall()
    except sqlite3.Error as exc:
        self._raise_database_error("list", exc)
    records: list[ScheduleRecord] = []
    for row in rows:
        try:
            records.append(self._row_to_record(row))
        except ScheduleRegistryDataError:
            raw_schedule_id = row["schedule_id"]
            schedule_id = self._diagnostic_schedule_id(raw_schedule_id)
            changed = await self._disable_malformed_record(raw_schedule_id)
            if changed:
                _logger.error(
                    "schedule.registry_data_disabled",
                    schedule_id=schedule_id,
                )
            records.append(self._diagnostic_record(schedule_id))
    return records
pause async
pause(schedule_id)

Disable future claims for a schedule without deleting its history.

Source code in src/marianne/daemon/schedule_registry.py
async def pause(self, schedule_id: str) -> None:
    """Disable future claims for a schedule without deleting its history."""
    await self._set_enabled(schedule_id, enabled=False)
resume async
resume(schedule_id)

Enable future claims for a schedule without recalculating recurrence.

Source code in src/marianne/daemon/schedule_registry.py
async def resume(self, schedule_id: str) -> None:
    """Enable future claims for a schedule without recalculating recurrence."""
    await self._set_enabled(schedule_id, enabled=True)
remove async
remove(schedule_id)

Remove a registration and all of its durable lease state.

Source code in src/marianne/daemon/schedule_registry.py
async def remove(self, schedule_id: str) -> None:
    """Remove a registration and all of its durable lease state."""
    if await self.get(schedule_id) is None:
        raise ScheduleRegistryError(
            f"Schedule {schedule_id!r} does not exist for removal"
        )
    cursor = await self._execute_mutation(
        "remove",
        """
        DELETE FROM schedules
        WHERE schedule_id = ?
          AND COALESCE(last_outcome, '') != ?
        """,
        (schedule_id, _REGISTRY_DATA_ERROR),
        schedule_id=schedule_id,
    )
    if cursor.rowcount != 1:
        await self._raise_lifecycle_mutation_refusal(
            schedule_id,
            missing_message=f"Schedule {schedule_id!r} does not exist for removal",
        )
claim_due async
claim_due(schedule_id, due_at, *, now=None)

Atomically claim one exact due identity, if it remains due and enabled.

Source code in src/marianne/daemon/schedule_registry.py
async def claim_due(
    self,
    schedule_id: str,
    due_at: float,
    *,
    now: float | None = None,
) -> DueClaim | None:
    """Atomically claim one exact due identity, if it remains due and enabled."""
    _require_epoch(due_at, name="due_at")
    current_time = time.time() if now is None else now
    _require_epoch(current_time, name="now")
    cursor = await self._execute_mutation(
        "claim due",
        """
        UPDATE schedules
        SET last_claimed_due_at = ?, updated_at = ?
        WHERE schedule_id = ?
          AND enabled = 1
          AND next_due_at = ?
          AND ? <= ?
          AND (last_claimed_due_at IS NULL OR last_claimed_due_at != ?)
        """,
        (due_at, time.time(), schedule_id, due_at, due_at, current_time, due_at),
        schedule_id=schedule_id,
        immediate=True,
    )
    if cursor.rowcount != 1:
        return None
    return DueClaim(schedule_id=schedule_id, due_at=due_at)
record_submission async
record_submission(schedule_id, due_at, run_id)

Persist a claimed tick's child identity without advancing recurrence.

Source code in src/marianne/daemon/schedule_registry.py
async def record_submission(self, schedule_id: str, due_at: float, run_id: str) -> None:
    """Persist a claimed tick's child identity without advancing recurrence."""
    _require_epoch(due_at, name="due_at")
    cursor = await self._execute_mutation(
        "record submission",
        """
        UPDATE schedules
        SET last_due_at = ?, last_run_id = ?, updated_at = ?
        WHERE schedule_id = ? AND last_claimed_due_at = ?
        """,
        (due_at, run_id, time.time(), schedule_id, due_at),
        schedule_id=schedule_id,
    )
    self._require_claimed_row(cursor.rowcount, schedule_id, due_at)
record_tick_outcome async
record_tick_outcome(schedule_id, due_at, outcome, *, next_due_at, dropped)

Persist a claimed tick outcome and caller-calculated next due time.

Source code in src/marianne/daemon/schedule_registry.py
async def record_tick_outcome(
    self,
    schedule_id: str,
    due_at: float,
    outcome: str,
    *,
    next_due_at: float,
    dropped: bool,
) -> None:
    """Persist a claimed tick outcome and caller-calculated next due time."""
    _require_epoch(due_at, name="due_at")
    _require_epoch(next_due_at, name="next_due_at")
    if next_due_at <= due_at:
        raise ValueError("next_due_at must be later than due_at")
    cursor = await self._execute_mutation(
        "record tick outcome",
        """
        UPDATE schedules
        SET last_due_at = ?,
            last_outcome = ?,
            next_due_at = ?,
            consecutive_drops = CASE
                WHEN ? THEN consecutive_drops + 1
                ELSE 0
            END,
            updated_at = ?
        WHERE schedule_id = ? AND last_claimed_due_at = ?
        """,
        (
            due_at,
            outcome,
            next_due_at,
            int(dropped),
            time.time(),
            schedule_id,
            due_at,
        ),
        schedule_id=schedule_id,
    )
    self._require_claimed_row(cursor.rowcount, schedule_id, due_at)
close async
close()

Close the async SQLite connection.

Source code in src/marianne/daemon/schedule_registry.py
async def close(self) -> None:
    """Close the async SQLite connection."""
    if self._conn is not None:
        await self._conn.close()
        self._conn = None

Functions: