Skip to content

recurrence

recurrence

Recurring-score controller joining durable schedules to normal submission.

Classes

RecurrenceController

RecurrenceController(registry, submit, schedule_tick, cancel_tick, is_active, *, now=utc_now, rng=None)

Own recurrence calculation, timer handles, and scheduled submissions.

Source code in src/marianne/daemon/recurrence.py
def __init__(
    self,
    registry: ScheduleRegistry,
    submit: SubmitJob,
    schedule_tick: ScheduleTick,
    cancel_tick: CancelTick,
    is_active: IsScheduleActive,
    *,
    now: Callable[[], datetime] = utc_now,
    rng: random.Random | None = None,
) -> None:
    self._registry = registry
    self._submit = submit
    self._schedule_tick = schedule_tick
    self._cancel_tick = cancel_tick
    self._is_active = is_active
    self._now = now
    self._rng = rng or random.Random()
    self._timers: dict[str, tuple[float, TimerHandle]] = {}
    self._lifecycle_locks: dict[str, asyncio.Lock] = {}
    self._registration_lock = asyncio.Lock()
    self._shutting_down = False
Methods:
restore async
restore()

Restore one live timer or one collapsed misfire per enabled schedule.

Source code in src/marianne/daemon/recurrence.py
async def restore(self) -> None:
    """Restore one live timer or one collapsed misfire per enabled schedule."""
    current = self._current_time()
    for record in await self._registry.list():
        if not record.enabled:
            continue
        if record.next_due_at <= current.timestamp():
            await self.handle_tick(
                CronTick(
                    entry_name=record.schedule_id,
                    score_path=str(record.score_path),
                    due_at=record.next_due_at,
                    timestamp=current.timestamp(),
                )
            )
            continue
        async with self._lock_schedules(record.schedule_id):
            refreshed = await self._registry.get(record.schedule_id)
            self._cancel_timer(record.schedule_id)
            if refreshed is not None and refreshed.enabled:
                self._arm_record(refreshed, current)
register async
register(score_path, config=None, *, before_wait=None, before_mutation=None, pin=None, require_schedule=False, registration_id=None)

Register or replace the current schedule declaration for one score.

Registration is the daemon-owned authority channel for source pinning: pin=None derives the opt-in from the score's schedule.pin_source_digest declaration, while an explicit pin=True/pin=False overrides it (for embedders that hold their own activation authority). The pin value stored in the registry row is the digest of the bytes read at registration, so a conscious re-registration amends the pin; mutable score bytes cannot rewrite the row between registrations.

Source code in src/marianne/daemon/recurrence.py
async def register(
    self,
    score_path: Path,
    config: JobConfig | None = None,
    *,
    before_wait: LifecycleProbe | None = None,
    before_mutation: LifecycleAdmission | None = None,
    pin: bool | None = None,
    require_schedule: bool = False,
    registration_id: str | None = None,
) -> ScheduleRecord | None:
    """Register or replace the current schedule declaration for one score.

    Registration is the daemon-owned authority channel for source pinning:
    ``pin=None`` derives the opt-in from the score's
    ``schedule.pin_source_digest`` declaration, while an explicit
    ``pin=True``/``pin=False`` overrides it (for embedders that hold their
    own activation authority). The pin value stored in the registry row is
    the digest of the bytes read at registration, so a conscious
    re-registration amends the pin; mutable score bytes cannot rewrite the
    row between registrations.
    """
    resolved_path = score_path.resolve(strict=False)
    async with self._registration_lock:
        source_config, source_digest = await self._load_score(resolved_path)
        if config is not None and config != source_config:
            _logger.info(
                "schedule.source_changed_during_registration",
                schedule_id=source_config.name,
                score_path=str(resolved_path),
            )
        config = source_config
        if require_schedule and config.schedule is None:
            return None
        priors = await self._registry.list()
        prior_ids = {
            prior.schedule_id
            for prior in priors
            if prior.score_path == resolved_path
            and prior.schedule_id != config.name
        }
        mutation_ids = tuple(sorted({config.name, *prior_ids}))
        if before_wait is not None and not before_wait(mutation_ids):
            raise RuntimeError(
                "Schedule lifecycle is already owned by another task"
            )
        async with self._lock_schedules(config.name, *prior_ids):
            if before_mutation is not None:
                before_mutation(mutation_ids)
            for prior_id in prior_ids:
                await self._remove_locked(prior_id)

            if config.schedule is None:
                if await self._registry.get(config.name) is not None:
                    await self._remove_locked(config.name)
                return None

            current = self._current_time()
            due = next_due_at(config.schedule, current)
            pin_declared = config.schedule.pin_source_digest
            pin_source = pin_declared if pin is None else pin
            await self._registry.upsert(
                config.name,
                config.name,
                resolved_path,
                config.schedule,
                source_digest,
                due.timestamp(),
                pinned_source_digest=source_digest if pin_source else None,
                registration_id=registration_id,
            )
            self._cancel_timer(config.name)
            record = await self._registry.get(config.name)
            if record is None:
                raise RuntimeError(
                    f"Schedule {config.name!r} disappeared after registration"
                )
            if record.enabled:
                self._arm_record(record, current)
            return record
handle_tick async
handle_tick(event)

Claim, resolve, record, and advance one exact recurring due identity.

Source code in src/marianne/daemon/recurrence.py
async def handle_tick(self, event: CronTick) -> None:
    """Claim, resolve, record, and advance one exact recurring due identity."""
    if event.due_at is None:
        _logger.error(
            "schedule.tick_missing_due_at",
            schedule_id=event.entry_name,
            score_path=event.score_path,
        )
        return

    async with self._lock_schedules(event.entry_name):
        replacement = await self._handle_tick_locked(event)
    if replacement is not None:
        await self.register(*replacement)
pause async
pause(schedule_id, *, score_path=None, before_mutation=None, on_authority=None, on_mutation=None)

Pause one schedule and cancel its pending timer.

Source code in src/marianne/daemon/recurrence.py
async def pause(
    self,
    schedule_id: str,
    *,
    score_path: Path | None = None,
    before_mutation: LifecycleAdmission | None = None,
    on_authority: LifecycleAuthority | None = None,
    on_mutation: LifecycleAuthority | None = None,
) -> ScheduleRecord:
    """Pause one schedule and cancel its pending timer."""
    async with self._lock_current_schedule(schedule_id, score_path) as record:
        if before_mutation is not None:
            before_mutation((record.schedule_id,))
        if on_authority is not None:
            on_authority(record)
        await self._registry.pause(record.schedule_id)
        if on_mutation is not None:
            on_mutation(record)
        self._cancel_timer(record.schedule_id)
        refreshed = await self._registry.get(record.schedule_id)
        if refreshed is None:
            raise RuntimeError(
                f"Schedule {record.schedule_id!r} disappeared while pausing"
            )
        return refreshed
resume async
resume(schedule_id, *, score_path=None, before_mutation=None, on_authority=None)

Resume one schedule and restore its one pending due identity.

Source code in src/marianne/daemon/recurrence.py
async def resume(
    self,
    schedule_id: str,
    *,
    score_path: Path | None = None,
    before_mutation: LifecycleAdmission | None = None,
    on_authority: LifecycleAuthority | None = None,
) -> ScheduleRecord:
    """Resume one schedule and restore its one pending due identity."""
    replacement: tuple[Path, JobConfig] | None = None
    resumed: ScheduleRecord | None = None
    async with self._lock_current_schedule(schedule_id, score_path) as authority:
        if before_mutation is not None:
            before_mutation((authority.schedule_id,))
        if on_authority is not None:
            on_authority(authority)
        await self._registry.resume(authority.schedule_id)
        record = await self._registry.get(authority.schedule_id)
        if record is None:
            raise RuntimeError(
                f"Schedule {authority.schedule_id!r} disappeared while resuming"
            )
        resumed = record
        current = self._current_time()
        if record.next_due_at <= current.timestamp():
            replacement = await self._handle_tick_locked(
                CronTick(
                    entry_name=record.schedule_id,
                    score_path=str(record.score_path),
                    due_at=record.next_due_at,
                    timestamp=current.timestamp(),
                )
            )
        else:
            self._arm_record(record, current)
    if replacement is not None:
        await self.register(*replacement, before_mutation=before_mutation)
    assert resumed is not None
    return resumed
remove async
remove(schedule_id, *, score_path=None, before_mutation=None, on_authority=None)

Remove one schedule and revoke its pending timer.

Source code in src/marianne/daemon/recurrence.py
async def remove(
    self,
    schedule_id: str,
    *,
    score_path: Path | None = None,
    before_mutation: LifecycleAdmission | None = None,
    on_authority: LifecycleAuthority | None = None,
) -> ScheduleRecord:
    """Remove one schedule and revoke its pending timer."""
    async with self._lock_current_schedule(schedule_id, score_path) as record:
        if before_mutation is not None:
            before_mutation((record.schedule_id,))
        if on_authority is not None:
            on_authority(record)
        await self._remove_locked(record.schedule_id)
        return record
describe async
describe(schedule_id=None)

Return durable schedule projections for later presentation layers.

Source code in src/marianne/daemon/recurrence.py
async def describe(self, schedule_id: str | None = None) -> list[ScheduleRecord]:
    """Return durable schedule projections for later presentation layers."""
    if schedule_id is None:
        return await self._registry.list()
    record = await self._registry.get(schedule_id)
    return [] if record is None else [record]
shutdown async
shutdown()

Cancel every controller-owned handle before timer-wheel shutdown.

Source code in src/marianne/daemon/recurrence.py
async def shutdown(self) -> None:
    """Cancel every controller-owned handle before timer-wheel shutdown."""
    self._shutting_down = True
    schedule_ids = list(self._timers)
    async with self._lock_schedules(*schedule_ids):
        for schedule_id in schedule_ids:
            self._cancel_timer(schedule_id)

Functions: