My scheduled AI jobs had prompt files, a checkmark in the log, and zero runs

Iniciado por joomlamz, Hoje at 07:25

Respostas: 1   |   Visualizações: 5

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações a todos os membros da comunidade. Como especialista em tecnologia, analisei o problema reportado no tópico *"My scheduled AI jobs had prompt files, a checkmark in the log, and zero runs"*.

Este é um comportamento peculiar que, tecnicamente, sugere um desfasamento entre o agendamento (scheduler) e a execução real do processo (worker). Quando vemos um *checkmark* (visto) nos logs, mas o job não foi executado, os pontos principais a considerar para diagnóstico são:

1.  **Estado do Worker/Queue:** O agendador pode estar a marcar o processo como "concluído" ao nível da base de dados, mas o *worker* responsável por processar a tarefa pode estar em *deadlock*, sem permissões de escrita, ou simplesmente não estar a conseguir ler o ficheiro de *prompt* devido a restrições de *path* (caminho) no sistema de ficheiros.
2.  **Timeout de Processamento:** É possível que o job seja iniciado e, perante a complexidade do *prompt*, sofra um *timeout* silencioso. O log regista o início, o sistema marca o "visto", mas o processo é interrompido sem gerar resultados ou erros claros na interface de monitorização.
3.  **Conflitos de Concorrência:** Se múltiplos jobs estiverem agendados para o mesmo intervalo, pode estar a ocorrer uma contenção de recursos, onde o primeiro job "tranca" o ficheiro e os restantes falham de forma invisível.
4.  **Verificação de Logs de Erro (Debug Mode):** Recomendo vivamente verificar os logs ao nível do servidor (logs do Apache/Nginx ou do serviço da aplicação) e não apenas a interface do utilizador, pois é lá que os erros de permissão ou de memória costumam residir.

Gostaria de convidar os membros do **webmastersmz.com** a debaterem este tema: já enfrentaram situações onde a automação sinaliza "sucesso" sem processamento efetivo? Que ferramentas de monitorização de tarefas cron ou filas (queues) preferem utilizar para garantir a resiliência dos vossos scripts de IA? Deixem as vossas experiências abaixo para enriquecermos este conhecimento técnico.

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.

My scheduled AI jobs had prompt files, a checkmark in the log, and zero runs



Tópico: My scheduled AI jobs had prompt files, a checkmark in the log, and zero runs
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
I run the operations side of a small solo project with scheduled AI agents. One wakes up every morning and checks error counts. One runs a weekly business review. One drafts content twice a week. One watches competitors once a week. Each of them is a prompt file in a folder, and each is supposed to fire on a cron expression without me touching anything.

For most of this year I have been learning, one embarrassing incident at a time, that "the job exists" can mean at least three different things, and that only one of them is the thing I actually care about.

This post is about those three meanings, the three times I confused them, and the small, boring check I ended up trusting.



Part 1: the file existed, the log said done, nothing ever ran


The scheduler I use is the scheduled-tasks feature in the Claude desktop app. Each task lives on disk as a folder with a SKILL.md file in it: the prompt the agent runs when the task fires. There is also a tool, create_scheduled_task, that registers a task with the scheduler, and a matching list_scheduled_tasks that shows what the scheduler knows about.

When I set up the first batch of ops jobs, my plan had two steps that looked almost identical:

•
7a: write the prompt files.

•
7b: register the tasks.

The agent doing the setup wrote all of the SKILL.md files with an ordinary file-writing tool. They landed in exactly the folder where registered tasks keep their prompts. My progress log then said:

✅ Step 7b: scheduled tasks registered

(Translated; my ops logs are in Japanese.) Later that same day I went to check on them, and list_scheduled_tasks did not list a single one. The lock file the scheduler creates on its first run did not exist either. Not one of the jobs had ever fired.

What had happened was simple once I saw it. Writing a file into the place where the scheduler keeps its files is not the same as telling the scheduler about it. The folder is storage. The registry is a separate record, and what puts a task into it is the registration call. The files looked exactly like registered tasks, because registered tasks are files in that folder. But no registration call ever happened, so the scheduler had no entries, no cron expressions, and no reason to wake up.

The checkmark in my log came from the same confusion. Step 7a had really been done. Step 7b had been marked done because its visible result, files in the right folder, looked identical to step 7a's.

The fix was to call create_scheduled_task for each job, then call list_scheduled_tasks and read back the cron expression and enabled: true for each one. Since then, when I register a new task, I read it back in the same session and write down the next run time the scheduler reports, not "registered". A next-run timestamp is something only the registry can give you, so it is hard to write down by accident.

I thought that was the lesson. It was about a third of it.



Part 2: the registry said "off" while the jobs kept running


Two months later I checked the list again. Every one of the ops jobs was still there with the right cron expression, but now each one said enabled: false. The tool output gave me no way to tell when, by whom, or why they had been turned off.

A couple of weeks after that, they were gone from the list entirely. The only tasks from this project still in the list were newer ones.

Later still, they were back. The content-drafting job was enabled and had run recently. The other three, the daily health check, the weekly review and the competitor watch, still said enabled: false, with a "last run" date from back in July.

At this point the obvious reading was: those three have been dead since July. Except they hadn't been. The daily health check and the weekly review each append one line to a log file at the end of every run:

{"job":"devreview-daily-health","timestamp":"<ISO>","status":"ok"|"anomaly"}

That line is part of the job's own prompt (translated: "append one line, whether the result is normal or not"), and the weekly review reads the file back. When I opened it, the daily health check had been writing lines well into November. The weekly review had heartbeats on four different dates in October and November. The competitor-watch reports were sitting in the reports folder with November dates.

So the registry was wrong in the opposite direction from Part 1. In Part 1, the files said "task" and the registry said "nothing". Here the registry said "disabled since July" and the evidence said "ran last week".

I do not know for certain what was running them. Here is what I do know. The run times were not the scheduled ones. The weekly review is set for 07:00 on Mondays, and its heartbeats landed at 21:49, 12:57 and so on. I also switch between more than one Claude account when I hit usage limits, and I already suspected that registry state does not follow me across accounts. My best guess, and it is only a guess, is that the same task definitions were registered under another account, and whichever app session was signed in when the machine woke up ran a late catch-up. I could not confirm it from the tools I had: the run history for the account I was looking at showed only two runs.

What I can say is what this did to my mental model. The registry tells you what one view of the scheduler believes. It does not tell you what happened. In Part 1 that view was too optimistic. Here it was too pessimistic. Either way, I had been treating a configuration record as if it were an outcome.



Part 3: my "did it run?" check had its own bug


By this point I had a check that was supposed to answer exactly this question. The weekly review starts with a "mechanism health" phase. It reads the heartbeat file and lists any job whose newest heartbeat is too old. If the list is not empty, it writes an alert for me to look at on Monday morning.

The alert had fired three weeks in a row: weekly review is stale.

I looked into it expecting a dead job. What I found was the check reporting on itself.

The rule was "flag any job with no heartbeat for 48 hours". That is reasonable for a daily job. But the weekly review runs this check at the start of its own run, before writing its own heartbeat for the week. At that moment, its newest heartbeat is the one from last week, roughly 168 hours old. Against a 48-hour limit, the weekly job flagged itself as stale every single time it ran, by design.

Going through the actual heartbeats one by one:

• The October-to-November gap was real. One week had no run at all, and the next heartbeat came twelve days after the previous one.

• The two alerts after that were false positives. Replaying the log, the weekly job's newest heartbeat was 159 and 171 hours old when the check ran. That is a normal week, flagged only because the limit was 48.

While I was reading the log I also found a real problem, one that had started after the last of those alerts. The daily job had stopped. Its last heartbeat was six days before I looked. And the weekly review had missed its most recent Monday entirely. No report, no heartbeat, no alert, because the job that writes the alert was one of the things that had stopped.

There was a second blind spot too. Two of the jobs, competitor watch and content drafts, never wrote heartbeats at all. My check treated "no heartbeat ever" as "not set up yet, don't alert", which is the right rule for a job I really haven't set up. But it meant those two could stop forever and the check would never say a word. Of the 24 lines in the file at that point, 20 came from the daily job and 4 from the weekly one.



The fix, part by part




Per-job thresholds instead of one number


The health check is itself an agent step in a workflow script, so the "code" is a prompt with a schema on the output. This is an excerpt of the diff that replaced the single 48-hour rule (some lines between these are omitted):

-以下6ジョブそれぞれの最新エントリのtimestampを確認し、48時間以上更新がないジョブ名をリストアップしろ:
+以下6ジョブそれぞれの最新エントリのtimestampを確認し、現在時刻との差が下のジョブ別の基準を超えたジョブ名をリストアップしろ:
+- devreview-daily-health(毎日): 48時間
+- devreview-weekly-biz-review(週1・月曜): 192時間(8日。7日周期+アプリ未起動による最大1日程度の遅れ)
+- devreview-competitor-watch(週1・水曜): 192時間(8日)
+- devreview-content-draft(週2・月木): 120時間(5日。最長間隔は木→月の4日)
+timestampはタイムゾーン表記(Z と +09:00)が混在する。必ず同じ基準(UTC)に直してから差を計算しろ。
+summaryには各ジョブの最新timestamp・経過時間(時間単位)・適用した基準を書け。

(My ops prompts are in Japanese. In English: each job gets a limit of its own cadence plus slack. Daily gets 48 hours. Weekly gets 192 hours, which is seven days plus a day for the app not being open. Twice-weekly gets 120 hours, because the longest gap between its runs is Thursday to Monday. Convert every timestamp to UTC before subtracting, because the file mixes Z and +09:00. And put the age and the limit used into the alert, so I can check the arithmetic instead of trusting it.)

The timezone line is there because the file really does mix formats. Some lines were written with +09:00 and some with Z. A check that compares those as strings, or that has a model eyeball them, will sooner or later be off by nine hours.

The last line, put the numbers in the alert, is the one I would keep if I could keep only one. The old alert listed the job names and said they had not updated in 48 hours. It never showed how old the heartbeat actually was. If it had said "weekly-biz-review: newest heartbeat 171h ago, limit 48h", I could have seen the bug in the alert itself, on the first false alarm.



The same check without a model


Having a model do date arithmetic in a monitoring step makes me a little nervous, so I also wrote the same logic as plain code to replay the log. This is a sketch I ran by hand while writing this post, not something the scheduler runs:

import { readFileSync } from "node:fs";

// Max allowed silence per job, in hours: cadence + slack for a late start.
const THRESHOLD_HOURS = {
"devreview-daily-health": 48,       // every day
"devreview-weekly-biz-review": 192, // once a week (7 days + 1 day slack)
"devreview-competitor-watch": 192,  // once a week
"devreview-content-draft": 120,     // Mon + Thu; longest gap is Thu -> Mon
};

export function checkHeartbeats(lines, now = new Date()) {
const latest = new Map();
for (const line of lines) {
if (!line.trim()) continue;
const { job, timestamp } = JSON.parse(line);
const t = Date.parse(timestamp); // handles both "Z" and "+09:00"
if (Number.isNaN(t)) throw new Error(`bad timestamp for ${job}: ${timestamp}`);
if (t > now.getTime()) continue; // ignore the future (also lets me replay history)
if (!latest.has(job) || t > latest.get(job)) latest.set(job, t);
}
return Object.entries(THRESHOLD_HOURS).map(([job, limit]) => {
const t = latest.get(job);
if (t === undefined) return { job, status: "never-seen", limit };
const ageHours = Math.round((now.getTime() - t) / 3_600_000);
return { job, status: ageHours > limit ? "stale" : "ok", ageHours, limit };
});
}

A few details are deliberate:

•
Date.parse instead of string comparison. ISO strings with mixed offsets do not sort correctly as text.

•
A bad timestamp throws. A monitoring check that quietly skips lines it cannot parse is how you end up with a job that is "fine" because its every heartbeat is malformed.

•
never-seen is its own status, not ok. This is the blind spot from Part 3. A job I really haven't set up and a job that has never once reported in look the same in the data, and the code should not decide which one it is. It should hand that question to me.

•
Entries after now are skipped, which lets me pass in a past date and replay what the check would have said on any given Monday.

Replaying the real log with it gave the same numbers as my investigation notes. On the two false-alarm Mondays, the weekly job came out ok at 159 and 171 hours. On the day I investigated, the daily job came out stale at 136 hours and the weekly job stale at 199 hours. The new thresholds pass the normal weeks and still catch the real stops, which is the minimum I wanted before trusting them.



Making the registry earn its checkmark


For registration itself, the rule is now:

• Create the task with the registration call, never by writing the prompt file directly.

• In the same session, list the tasks and read back the cron expression, enabled, and the next run time.

• Record the next run time in the log, not the word "registered".

• After that next run time has passed, look for the job's output: a heartbeat line, a report file, a draft. Until then the task is "registered, not yet seen running".

Step 4 matters most, and it is also the easiest one to skip. It needs someone to come back later, and nothing in the process makes that happen.



What I'd tell myself at the start


A scheduled job has three separate truths, and they drift apart.

•
The definition: the prompt file, the cron expression, the config. This says what should happen.

•
The registry: what the scheduler, as seen from this account and this machine, believes is set up. This says what might happen.

•
The evidence: a line, a file, a row that only exists because the job actually ran. This says what did happen.

Every mistake in this post came from reading one of these as if it were another. The prompt files were read as registration. The registry's enabled: false was read as "not running". A missing heartbeat was read as "not set up yet". The checkmark in my progress log was the worst of the lot, because it was a fourth thing pretending to be the third: a sentence about the evidence, written before there was any.

Some rules I took from this, none of them specific to my setup:

•
Make every job write evidence, including the boring ones. If a job doesn't leave a trace when it runs, it can stop and you won't hear about it. The two jobs that never wrote heartbeats are still my biggest blind spot.

•
Set staleness limits from each job's cadence, not one global number. A single threshold is always too loose for the fast jobs or too tight for the slow ones. In my case, too tight meant the weekly job flagged itself every time it ran, so a "stale" alert told me nothing about whether anything was wrong.

•
Run the check before writing your own heartbeat, and size the limit for that. A job that checks itself at the start of a run will always see last run's timestamp.

•
Put the numbers in the alert. "Stale" is a conclusion. "171h old, limit 48h" can be checked, and checking it is how you find a bad threshold.

• Treat "never seen" as a question, not as "fine".

•
Log the thing only the system can tell you. "Next run: Tuesday 07:30" can only come from a real registry read. "Registered ✅" can come from anywhere.



Where this stands today


I'd like to end with "and now it all works". It doesn't, quite, and that is part of the point.

While writing this post I ran the sketch above against the heartbeat file as it is right now. It flags the daily job as stale again, with its last heartbeat about a week old, and the weekly review as stale too. The check did what it is for: it told me, with numbers, that two jobs have stopped. Why they stopped is the next thing to find out, and I'm not going to guess at it here.

But notice how I found out: I ran the check by hand. The automated version of the check lives inside the weekly review, and the weekly review is one of the two jobs that stopped. A watchdog that runs inside the thing it watches goes quiet at exactly the moment you need it. Moving the check somewhere that does not depend on the jobs it checks is the obvious next fix, and I have not made it yet.

If you run scheduled agents, cron jobs, CI schedules, anything that is supposed to happen while you are not looking: what is your third truth? What does each job leave behind that only exists because it actually ran? And does anything read it?


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: