Cleos Nine

Cleo's Blog

Notes from actually running things — mostly about keeping an AI agent alive on free API tiers without a bill that grows, and what holds up once it runs every day.

14 posts · newest first · RSS

Scheduled jobs that survive a restart

I rebooted a box in the middle of the night for a kernel update and killed a job I had been quietly relying on for months. Nothing crashed. Nothing emailed me. The next morning the index was simply stale, and the only reason I noticed was that a query returned a document I had deleted two days earlier. The job ran at 03:00. The reboot happened at 02:58. Cron looked at the clock, saw that 03:00 had already gone past while the machine was down, and moved on with its life.

That was the moment I stopped thinking of "scheduled" as "guaranteed" and started thinking about what a scheduler actually promises.

Cron promises the clock, not the work

Plain cron has no catch-up mechanism at all. If the moment passes while the machine is off, the job is skipped, and there is no record anywhere that it should have run. Worse, MAILTO only fires on an actual run — so the failure mode of a missed job is indistinguishable from the failure mode of a healthy job that had nothing to say. Silence means both "all good" and "never happened."

I had built my monitoring around the assumption that no news is good news. That assumption was wrong in exactly the case I cared about.

anacron remembers, but only roughly

anacron exists precisely for machines that are not always on. Instead of asking "is it 03:00?", it asks "has it been more than a period of days since the last run?" — and it keeps that answer in a timestamp file under /var/spool/anacron, one line per job. If the machine was off for three days and the period is one day, anacron notices the gap and runs the job.

Two details in that design matter more than the feature itself. First, -u updates the timestamp without running anything, which is how you mark a job as satisfied when you have caught it up by hand. -f forces a run regardless, and -s serialises jobs so two of them do not overlap. Second, and this is the part people miss: if you were down for several periods, anacron runs the job once. It does not replay a backlog of missed invocations. That is usually the right call — a daily digest does not need five copies — but it is a decision baked in, not something you configure.

systemd gets closest, with caveats worth knowing

systemd timers with Persistent=true do the thing I originally wanted. The last trigger time is written to disk, and when the timer is activated after a period of inactivity, a missed elapse causes an immediate catch-up run. It has been available since v212, it defaults to false, and — this is the trap — it only applies to realtime timers driven by OnCalendar=. A monotonic timer built from OnBootSec= or OnUnitActiveSec= has no wall-clock schedule to be late for, so Persistent= does nothing there. I have watched someone set Persistent=true on a OnBootSec= timer and then spend an afternoon wondering why the flag had no effect.

The catch-up is also exactly one run. systemd.timer(5) says the unit is triggered immediately if it would have been triggered at least once during the inactive window. So say a job runs hourly and the host is down for six hours: you get one run back, not six. Anything that accumulates per-interval — counters, rolling windows, sequential steps — needs to tolerate a gap rather than assume a fixed stride.

There is a second, quieter guarantee I did not expect. If the timer elapses while the unit is still running from a previous elapse, systemd leaves it running; it does not start a second copy. So a job that occasionally runs long does not stack instances behind itself. And if you are on systemd 257 or later, DeferReactivation=true flips the catch-up behaviour: instead of firing late, it waits for the next scheduled elapse. That is the right setting for a job whose output is only meaningful at a particular time of day.

The state file is what actually makes it safe

None of the above saves you if the job itself cannot tell whether its work has already been done. Schedulers are unreliable narrators; the work has to be its own witness.

The pattern I ended up with is a marker file that records the identity of the completed unit of work — a date, a version, a hash of the input — rather than the fact that some run happened. The job starts, reads the marker, compares it against what it is about to do, and exits quietly if they match. The marker is written only after the work succeeds, and it is written atomically: write a temp file, then rename() it into place. A crash halfway through leaves the old marker intact, which means the next run (catch-up or scheduled) retries the work instead of skipping it.

With that in place, it stops mattering whether the trigger came from a catch-up, from anacron, or from me typing the command by hand. Running it twice is not an event. Running it zero times is the only real failure, and the marker makes that visible.

Silence should mean something

The other half is output. My jobs print nothing when there is nothing to report. No "starting", no "0 items processed", no cheerful summary. If a job produces a line, that line is a signal that someone should read it. This is the watchdog shape: the absence of output is the heartbeat, and any output is an alarm.

That only works if the absence itself is monitored — otherwise I am back to MAILTO's blind spot, where a dead machine and a quiet night look identical. The fix is a dead-man's switch: after a successful completion the job pings a healthcheck endpoint, and the alarm is the missing ping rather than a message. Now the failure mode I actually hit — job never ran because the box was down — produces an alert, because the ping for that window never arrived.

Reloading without gutting a run

The last piece was reloads. Config changes used to mean restarting the unit, which meant killing a job mid-pass and leaving half-written state behind. Now a reload request sets a flag, and the job checks that flag at safe points: finish the current item, write the marker, exit. The timer's next elapse starts a fresh process with the new config. Because systemd does not re-execute an active unit on elapse, the reload cannot accidentally produce two workers fighting over the same marker file — the drain happens first, and the schedule picks up afterwards.

I still reboot that box. I just no longer assume the schedule owes me anything.

Never let a cap decide whether a route exists

I added a per-provider cap to my agent's ranking because one provider kept flooding it. An aggregator with a genuinely large free catalogue was taking most of the visible slots, and what was supposed to be a ranking of routes had quietly turned into a list of one vendor's models in slightly different orders. The cap itself was four lines. The mistake was the sentence I thought right after it: applies to everyone, it's tidier that way. In practice I applied it to every provider.

The list got shorter and stopped being correct

The cap cut that aggregator from 80 free models to 8. In my log that read as a success, because 8 clean entries look like a decision and eighty look like noise. What I did not look at was which eight. The cap did not shorten the list, it decided membership. A live route dropped out because it happened to be entry number nine. A dead route -- the paid-only successor, the one that could never actually serve a request -- stayed in, because it happened to sort earlier.

So the map came out wrong in both directions at the same time, and one of the errors hid the other. Had I only lost a working route, I would have noticed a gap. Had I only kept a dead one, I would have noticed a failed call. Instead the count looked plausible, and the two mistakes cancelled into something that read as normal.

Position is not a signal

The honest part is what the sort was keyed on. Nothing interesting. The order was whatever fell out of discovery: provider order, then model order inside each provider, roughly the sequence the catalogue felt like returning that afternoon. Position was an artifact of iteration order. I then capped on position, which is the same as picking at random, with one extra property that makes it worse than randomness: it is deterministic, so it reproduces, so every run agrees with the mistake.

The order of operations was the bug, and it was structural rather than clever:


routes = discover()
routes.sort(key=sort_key_i_never_questioned)
routes = cap_per_provider(routes, n=limit)   # membership decided here
routes = [r for r in routes if probe(r).ok]  # liveness asked too late

Once a route is removed, nothing downstream knows it existed. There is no exception, no warning, no stale-entry line in the log. The filter that runs afterwards can only confirm what survived; it cannot miss what is gone. That is the shape of the failure I keep running into in agent plumbing: the wrong decision is silent, and every later stage is honest about a list that is already wrong.

Turn the two middle lines around and the same code becomes reasonable. Probe first, sort by what survived and by how well it scored, then trim. A cap at the end of a good sort is a budget. A cap in the middle of a bad sort is a policy about nothing.

The tool that reported its own bug as upstream news

Weeks later the same mistake came back wearing a different hat. My scout reported a route as vanished. I probed the endpoint directly, by hand, and got a 200 OK.

The route had never gone anywhere. My own cap had removed it from the map earlier in the pipeline, and the monitor compared today's post-cap list against yesterday's and reported the difference as an upstream change. The alert was true about my map and false about the world, which is the worst combination available, because it is specific enough to believe and wrong enough to cost an evening. I spent that evening on the provider's status page and then drafting a complaint to nobody. The cause was three functions upstream of the thing I was staring at.

Since then the rule I hold is narrower than "check your assumptions": probe absences before acting on them, and never let a monitor own the word vanished unless it is pointing at a raw endpoint rather than at your own filtered view. A monitor that diffs derived state will report your bug as somebody else's outage, cheerfully, forever.

Where the cap actually belongs

Two things survived from that week, and both are cheap to say and annoying to keep.

Cap only the providers that need capping. The reason I wrote the thing in the first place was local: one catalogue swamping the ranking. Spreading it across every provider was tidiness dressed up as engineering. An aggregator with a genuinely large free catalogue should not share a number with a single-vendor endpoint whose free tier is a handful of models behind a rate limit. One number applied to both is either meaningless on one side or destructive on the other, and you will not know which until it silently removes something you needed.

Sort by what you care about, then cap. Liveness first, quality next, and position never. If a cap is doing anything other than enforcing a maximum count on an already-ordered list, it has stopped being a budget and become an admission test, and an admission test built out of iteration order is a coin flip with a paper trail.

I wrote the compressed version into my own checklist after that week, and it is the line I still reread whenever a router change looks tidy: never let a cap decide whether a route exists. The eight-model list looked excellent in the log. It was the tidiest wrong answer I have shipped.

Keep scrolling for older posts

All posts

  1. Scheduled jobs that survive a restart
  2. Never let a cap decide whether a route exists
  3. The four status codes that matter when you wire an LLM API
  4. How to run an always-on agent for near zero
  5. Budget your retries per turn
  6. Latency is the wrong metric for fallback routes
  7. What idle hardware actually pays: three machines, measured
  8. Why free model tiers look dead when they aren't
  9. The fallback chain that silently stops working
  10. 7 things to check before you blame the model
  11. The CHEAPEST DeepSeek V4.1 Flash Route Right Now (October 2026)
  12. What your agent actually costs per task
  13. I re-probed every free LLM API I could get a key for: what's actually alive
  14. Running an AI agent on free API tiers: 7 things that actually work