Something can happen because time passed, and land somewhere worth reading
Nothing in LLeMbas ever happened on its own. Every reply was downstream of
somebody pressing Send, and the one exception -- jobs.wake, waking a chat when a
background job finishes -- was downstream of a command they had run. PLAN.md
never listed scheduling as unbuilt because services/chat.py:618 had recorded it
as a decision: "a scheduler is a whole new concern for a single-worker
application". This is that concern, taken on deliberately, plus the two places
its output goes.
Reports first, because it is useful with no scheduling at all. A report is not a
Chat with one Message in it: it has no turns and no reply, it is read top to
bottom, and it must be writable with no chat behind it -- being the fallback for
a run whose own chat has gone. As a Chat it would need a sidebar row per daily
report, a title that regenerates itself, a composer to suppress and a bubble with
a rewind button around something that is not a turn. The section's character is
enforced by absence: nothing under reports/ includes the composer or renders
chat/_message.html, so there is no sse-connect anywhere and nothing on those
pages *can* start a generation. The test reads that off the OpenAPI schema, not
by walking app.routes -- this FastAPI keeps an included router wrapped rather
than flattening it, so the walk finds nothing and the assertion passes for the
wrong reason.
rule.py is pure, total, and was finished before anything called it. No session,
no wall clock, nothing that raises: validate clamps what it recognises, drops
what it does not, and answers {} for prose -- at which point the caller shows the
manual form. It had to be that way because the compile step's output is model
output that becomes a *timer*, which is the sharpest case of hard rule 6 here.
The invariant, pinned: anything validate accepts has a computable next
occurrence. A schedule that can never fire looks exactly like a working one on
every screen it appears on.
Wall-clock and elapsed time are kept apart because they mean different things.
at.times are wall-clock in the owner's zone, so 15:00 stays 15:00 across a
daylight-saving change -- that is what "every Monday at 3PM" means. every is
elapsed real time, so six hours stays six hours across a 23- or 25-hour day --
that is what a timer means. Conflating them gets one of the two wrong twice a
year. A time inside the spring-forward gap fires at the first minute that exists;
left to zoneinfo's own resolution it lands an hour away wearing a wall-clock time
that did not happen, and a daily 02:30 report vanishing once a year on a machine
nobody watches is the failure this file is arranged around.
The ticker claims and commits *before* it fires. The other order is a hot loop: a
firing that raises is retried every tick for ever against whatever it was that
failed, and the only symptom is load. Its blanket except is copied from the
terminal reaper for a sharper reason -- a ticker that dies on one bad row stops
every schedule on the instance and says nothing at all. No request fails, no
reply errors, no dot appears. The reports simply stop.
Three rules that look like bugs from outside: a firing arriving while the chat is
still answering queues rather than starting a second reply, and past max_queued
is skipped with the reason on the row; Run now does not advance next_fire_at, or
testing a schedule silently consumes the run it was testing; resuming recomputes
from now, or a schedule paused for a month fires the instant it comes back, once
per occurrence it missed. Catching up lives in the sweep and not in a startup
hook, because a suspended host and a long stall reproduce "its time passed while
nothing was running" with no restart to hang one on.
services/wake.py is the lock discipline extracted rather than copied. A finished
job and a due schedule are the same problem, and both depend on there being no
await between the running_for check and the writes; two lock dictionaries for one
invariant is how one of them drifts. jobs.wake is now a caller that supplies
wording, and _completion_text stayed exactly where it was because tool.background
quotes its opening sentence.
A scheduled run has no reader, so ask_user is withdrawn from resolve_tools rather
than merely discouraged in core.unattended -- a rule living only in a system
message is one a page the model just read can argue with, and a parked question
holds the reply for the whole approval_timeout with nobody to answer it. For the
same reason a task chat may not be an agent chat in v1: Manual, Edit and Plan all
stop to ask on RISK_EXECUTE, so the only two outcomes would be unattended
execution and a reply that stalls. That deserves its own pass.
Messages is bounded in the request and unbounded on disk. Only the latest chunk
is sent; everything else stays exactly where it was written. Nothing is folded
into text and nothing is deleted -- the visible conversation is identical either
way, so destroying the older rows would buy only disk, against being irreversible
and losing every attachment and tool call in the range, and it would contradict
the rule compaction already holds. should_compact refuses this kind for the
matching reason: two mechanisms narrowing one transcript is how a summary ends up
summarising a summary. The history route is the mirror of thread_tail and keeps
its four properties; the fifth is its own, that prepending moves the scroll
position, so app.js records scrollHeight before the swap and adds the difference
back after.
An empty Chat.kind meant "both sides of the switch" and had been read as "no
filter" since there were only two of them. The sidebar passes "" precisely when
agent chats are switched off -- so the moment a third kind existed, every task
chat and every Messages conversation appeared in somebody's ordinary chat list,
on exactly the instances whose owners would never think to look. KINDS stays the
two-sided fork, because set_sidebar_kind validates against it and a third entry
there makes the tree filterable to a side with no button to leave it; ALL_KINDS
is what a row may be. Both narrowings are pinned, because they are two
implementations of one rule and only one of them is SQL.
Per-user timezone had to exist for any of this: harness.py:179 was telling every
reader the *server's* idea of the date, which is survivable while the answer is
prose and stops being survivable the moment somebody says "every Monday at 3" and
something has to work out when that is.
Three things were caught by a test being wrong rather than by the code being
wrong. The task-chat "no composer" assertions were passing against a page
rendering its no-models-configured branch. A permission test asserted the same
thing twice because the administrator bypasses every permission. And every
Messages test passed with default_model never called, because none of them
configured a model -- so the pair it returns was being assigned straight to
model_id, and SQLite refuses a tuple in a String column. The fixtures now say why
they exist.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
"""Making, changing and stopping a schedule.
|
||||
|
||||
The row-level half: what the routes and the tools both need, so neither has its
|
||||
own idea of what creating a schedule involves. `services/schedule/` holds the
|
||||
machinery — when it next comes due, and what happens when it does.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session as DBSession
|
||||
|
||||
from lembas.db.models import (
|
||||
KIND_TASK,
|
||||
ORIGIN_USER,
|
||||
ORIGINS,
|
||||
TARGET_CHAT,
|
||||
TARGETS,
|
||||
Chat,
|
||||
Schedule,
|
||||
User,
|
||||
)
|
||||
from lembas.services import settings_store
|
||||
from lembas.services.schedule import clock
|
||||
from lembas.services.schedule import rule as rule_service
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
MAX_TITLE_CHARS = 200
|
||||
MAX_INSTRUCTION_CHARS = 8000
|
||||
|
||||
|
||||
class ScheduleError(Exception):
|
||||
"""Something a person needs told, in words they can act on."""
|
||||
|
||||
|
||||
def visible(user: User | None):
|
||||
if user is None:
|
||||
return select(Schedule).where(Schedule.id.is_(None))
|
||||
return select(Schedule).where(Schedule.user_id == user.id)
|
||||
|
||||
|
||||
def get(db: DBSession, schedule_id: str, user: User | None) -> Schedule | None:
|
||||
schedule = db.get(Schedule, schedule_id)
|
||||
if schedule is None or user is None or schedule.user_id != user.id:
|
||||
return None
|
||||
return schedule
|
||||
|
||||
|
||||
def for_chat(db: DBSession, chat: Chat) -> Schedule | None:
|
||||
"""The schedule a task chat belongs to, if any."""
|
||||
return db.scalars(select(Schedule).where(Schedule.chat_id == chat.id)).first()
|
||||
|
||||
|
||||
def count_for(db: DBSession, user: User) -> int:
|
||||
return int(
|
||||
db.scalar(
|
||||
select(func.count()).select_from(Schedule).where(Schedule.user_id == user.id)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
|
||||
|
||||
def create(
|
||||
db: DBSession,
|
||||
*,
|
||||
owner: User,
|
||||
title: str,
|
||||
instruction: str,
|
||||
rule: dict,
|
||||
request: str = "",
|
||||
target: str = TARGET_CHAT,
|
||||
model_id: str = "",
|
||||
origin: str = ORIGIN_USER,
|
||||
) -> Schedule:
|
||||
"""Write a schedule and the chat it fires into.
|
||||
|
||||
**The chat is created here, with the schedule**, and this is the one place
|
||||
"chats are created lazily" is deliberately bent. That rule exists so an
|
||||
opened-and-abandoned chat never appears in the sidebar; a task chat is not
|
||||
opened and abandoned, because creating it *is* the act. It also has to exist
|
||||
before the first firing, which may be days away and will have nobody
|
||||
present to make one.
|
||||
|
||||
A task chat is never `KIND_AGENT`. Scheduling one would mean running
|
||||
commands on a timer with nobody watching — and since every mode except Auto
|
||||
stalls waiting for an approval that will not come, the only two outcomes are
|
||||
"unattended execution" and "does nothing". That deserves its own pass with a
|
||||
mode built for it, not a flag here.
|
||||
"""
|
||||
clean = rule_service.validate(rule)
|
||||
if not clean:
|
||||
raise ScheduleError(
|
||||
"That does not describe a time anything could run at. "
|
||||
"Say when it should happen — a date and time, or how often."
|
||||
)
|
||||
if rule_service.next_after(clean, datetime.now(tz=UTC), zone=clock.zone_for(owner)) is None:
|
||||
# Belt and braces over `validate`'s own invariant. A schedule that can
|
||||
# never fire looks exactly like a working one on every screen it appears
|
||||
# on, so it is refused at the only moment somebody is present to be told.
|
||||
raise ScheduleError("That schedule has no next run — its time has already passed.")
|
||||
|
||||
limit = int(settings_store.schedules(db).get("max_per_user") or 20)
|
||||
if count_for(db, owner) >= limit:
|
||||
raise ScheduleError(
|
||||
f"You already have {limit} schedules, which is the most this instance allows. "
|
||||
"Remove one before adding another."
|
||||
)
|
||||
|
||||
chat = Chat(
|
||||
user_id=owner.id,
|
||||
kind=KIND_TASK,
|
||||
title=(title.strip() or "Scheduled task")[:MAX_TITLE_CHARS],
|
||||
model_id=model_id or "",
|
||||
)
|
||||
db.add(chat)
|
||||
db.flush()
|
||||
|
||||
schedule = Schedule(
|
||||
user_id=owner.id,
|
||||
title=(title.strip() or "Scheduled task")[:MAX_TITLE_CHARS],
|
||||
request=(request or "").strip()[:MAX_INSTRUCTION_CHARS],
|
||||
instruction=(instruction or "").strip()[:MAX_INSTRUCTION_CHARS],
|
||||
rule_json=clean,
|
||||
target=target if target in TARGETS else TARGET_CHAT,
|
||||
chat_id=chat.id,
|
||||
model_id=model_id or "",
|
||||
origin=origin if origin in ORIGINS else ORIGIN_USER,
|
||||
enabled=True,
|
||||
next_fire_at=rule_service.next_after(
|
||||
clean, datetime.now(tz=UTC), zone=clock.zone_for(owner)
|
||||
),
|
||||
compiled_at=datetime.now(tz=UTC),
|
||||
)
|
||||
db.add(schedule)
|
||||
db.commit()
|
||||
return schedule
|
||||
|
||||
|
||||
def update(
|
||||
db: DBSession,
|
||||
schedule: Schedule,
|
||||
*,
|
||||
owner: User,
|
||||
title: str | None = None,
|
||||
instruction: str | None = None,
|
||||
rule: dict | None = None,
|
||||
target: str | None = None,
|
||||
) -> Schedule:
|
||||
"""Change a schedule. Absent arguments are left alone."""
|
||||
if title is not None and title.strip():
|
||||
schedule.title = title.strip()[:MAX_TITLE_CHARS]
|
||||
if instruction is not None:
|
||||
schedule.instruction = instruction.strip()[:MAX_INSTRUCTION_CHARS]
|
||||
if target is not None and target in TARGETS:
|
||||
schedule.target = target
|
||||
if rule is not None:
|
||||
clean = rule_service.validate(rule)
|
||||
if not clean:
|
||||
raise ScheduleError(
|
||||
"That does not describe a time anything could run at. "
|
||||
"Say when it should happen — a date and time, or how often."
|
||||
)
|
||||
schedule.rule_json = clean
|
||||
# Recomputed from now, and the count restarted: an edited schedule is a
|
||||
# new intention, and carrying the old `fired_count` into a new `count`
|
||||
# would silently spend most of it before the first run.
|
||||
schedule.fired_count = 0
|
||||
schedule.next_fire_at = rule_service.next_after(
|
||||
clean, datetime.now(tz=UTC), zone=clock.zone_for(owner)
|
||||
)
|
||||
if schedule.next_fire_at is None:
|
||||
raise ScheduleError("That schedule has no next run — its time has already passed.")
|
||||
db.commit()
|
||||
return schedule
|
||||
|
||||
|
||||
def set_enabled(db: DBSession, schedule: Schedule, *, owner: User, enabled: bool) -> Schedule:
|
||||
"""Pause or resume.
|
||||
|
||||
**Resuming recomputes from now**, never from the stored value. A schedule
|
||||
paused for a month would otherwise come back due — and with catching-up in
|
||||
the sweep, it would fire the moment it was switched on, having decided it
|
||||
was owed a run from four weeks ago.
|
||||
"""
|
||||
schedule.enabled = bool(enabled)
|
||||
if enabled:
|
||||
schedule.last_error = ""
|
||||
schedule.next_fire_at = rule_service.next_after(
|
||||
schedule.rule_json or {},
|
||||
datetime.now(tz=UTC),
|
||||
zone=clock.zone_for(owner),
|
||||
fired=schedule.fired_count or 0,
|
||||
)
|
||||
if schedule.next_fire_at is None:
|
||||
schedule.enabled = False
|
||||
schedule.last_error = "There are no runs left in this schedule."
|
||||
db.commit()
|
||||
return schedule
|
||||
|
||||
|
||||
def delete(db: DBSession, schedule: Schedule, *, keep_chat: bool = True) -> None:
|
||||
"""Remove a schedule, and by default keep its transcript.
|
||||
|
||||
Keeping is the default because deleting a conversation as a side effect of
|
||||
removing a timer is exactly the destructive default this codebase avoids
|
||||
elsewhere. The chat becomes an ordinary one so it is reachable again — a
|
||||
`KIND_TASK` chat with no schedule behind it would be in no list at all.
|
||||
"""
|
||||
chat = db.get(Chat, schedule.chat_id) if schedule.chat_id else None
|
||||
if chat is not None:
|
||||
if keep_chat:
|
||||
chat.kind = "chat"
|
||||
else:
|
||||
db.delete(chat)
|
||||
db.delete(schedule)
|
||||
db.commit()
|
||||
|
||||
|
||||
def describe(schedule: Schedule, *, owner: User | None) -> str:
|
||||
return rule_service.describe(schedule.rule_json or {}, zone=clock.zone_for(owner))
|
||||
Reference in New Issue
Block a user