📚 Encyclopedia

AI & Claude · updated 2026-11-02

Lifecycle of an async AI request (status machine, expiry, retries, failure)

procrastinaistate-machinetimeoutsretriescronwebhooksreliability

TLDR's AI posts are long-running jobs: the API hands a prompt to claude-service (ProcrastinAI's webhook runner for headless Claude) on another machine, and an answer arrives minutes later on a signed callback. Almost every reliability bug in the feature came from the API's view of a job drifting from reality: posts stuck in "Thinking..." forever, or marked timed out while the AI was still working. The lessons generalize to any webhook-style job system.

The status machine

pending -> processing -> answered | error | cancelled (the last is the literal value in code). Until October 2026 this lived in post metadata next to the request id, session id, model, project, timeout and retry count, overwritten on every turn. It now lives in a job table, one row per turn (see "Separate the job from the content" below). - error is a real terminal state (added v1.52.0). Before it, failures were "answered" with an error text, which made them indistinguishable from success in filters and UI. - One function writes terminal failures (failRequest: post the error response, set error, add the failure reaction). Callers decide separately whether to push a notification. - Cancel refuses anything already terminal.

Rule 1: never mark progress before the hand-off succeeds

The trigger set processing before the HTTP enqueue, and the request id was only stored on success. When the desktop had suspended (tunnel half-dead: the forwarded port still listened but nothing answered, so the enqueue timed out with 0 bytes), the post sat in "processing" with no request id. Fix: if the enqueue fails (curl error or non-202), fail the request immediately with the reason. Nothing can ever call back for a job the service never received.

Rule 2: the sweeper must see every non-terminal row

The expiry cron INNER-joined on request id, so rows without one were invisible to it. Use a LEFT join and age request-less rows from their last activity ("never dispatched to the AI service").

Rule 3: the timeout must match the executor's real worst case

The service runs the CLI with a per-attempt timeout and up to 3 attempts with backoff, so a 15-minute job can legitimately take about 46 minutes (3 x timeout + delays), and the API only hears back after the last attempt. A cron with a flat 20-minute cutoff posted "timed out" mid-attempt-2 while commits were still landing. Fix: - Per-job cutoff = max(20 min, 3 x job_timeout + retry delays + buffer), clamped, with an absolute cap (6 h). - Ask the executor before expiring: GET /status/{id}; skip anything still queued or processing (a sequential queue means waiting is not staleness). If the executor is unreachable, age-based expiry is correct, because no callback can arrive either. - When the executor holds work during an account usage limit (up to ~5.5 h), the 6 h cap still covers it.

Rule 4: your own error message must not block a retry

Continuing a thread bails out if "the AI already has the last word" (last response is from the AI user). The cron's timeout message is an AI response, so when the real retryable error arrived, the re-trigger silently no-opped and the post stayed pending forever. Fixes: on retry, trim trailing AI responses before the check (and treat an error thread as a retry); check the result of the re-trigger and close the job as failed if it did not start; sort same-second responses by id so the trim is deterministic.

Rule 5: retries of mutating prompts are dangerous

Each retry re-runs the same prompt. For a job like "do all the pending work" with tool access, attempts 2 and 3 re-ran it against a repo attempt 1 had already changed. Give big jobs a long enough per-attempt timeout (60 min) that they do not get killed and retried, and tell retries what the previous attempt left behind.

Rule 6: clear the old job's id before you mark the new one in progress

A third false-timeout bug: a user's follow-up instantly got "timed out", then the real answer arrived anyway. The trigger set processing before dispatching, and the new request id was written only after the executor accepted it. In that gap the post still carried the previous turn's request id (25 minutes old, finished). The per-minute sweep ran in the same second, saw an old id past its cutoff, asked the executor (which correctly said "not alive, finished"), and failed the new turn. Two fixes, both general: - When starting a turn, clear the old correlation id in the same step that sets processing, so a sweeper sees "never dispatched, aged from now". - A sweeper should re-read the row right before acting and skip it if the status or id changed since its SELECT (optimistic check).

Separate the job from the content

All of the bugs above share a root: one set of fields on the post stood for "the current job" and was overwritten every turn. TLDR finally split them (v1.61.0): an AI request is a job; the AI conversation stays a post. Keeping the thread a post keeps sharing, links, bookmarks, search, notifications and retention for free; only per-turn job state moved out. - ai_request table, one row per turn: post id (FK, cascade delete), the response that triggered it (NULL = the post body), the response that answered it, the executor's request id of the latest attempt (UNIQUE), status, model, project, attempts, timeout, error, and created / dispatched / finished times. - The post keeps only thread-level state (project, resume session id, timeout preference) plus a display mirror of the latest request's status and model, written by exactly one function, so feeds and filters keep working without joins. - Retries are counted per turn (max 3), so a flaky turn no longer uses up the next turn's budget. - Terminal writes are guarded: "fail this request" only closes a row that is still pending or processing, and only for that attempt; if the row is already closed it returns false and posts nothing. That ended duplicate error messages. - Dispatch records the executor id only if the row is still processing, so a cancel that lands during the HTTP call is not undone. - Callbacks are matched by executor id. Late success after an expiry or cancel is still delivered (an answer beats lost work); late errors on closed rows are ignored; only the latest turn may move the resume session id. Callbacks with unknown ids are ignored with a 200, except well-formed ids newer than the post's last dispatch, which are adopted (jobs dispatched by side channels such as a timer script). - The expiry sweep reads WHERE status = 'processing' from the job table and ages each row from its dispatch time (or creation time if never dispatched). The stale-id race above cannot happen. - Users get history for free: an endpoint lists a thread's turns (author or admin only), shown in a long-press dialog with turn, retries and request id. - Backfill: existing threads got one row each for their last turn; earlier turns were never recorded.

Testing a lifecycle change on production safely

The table change was verified with a 25-check harness that ran on production inside a transaction that was rolled back at the end, against a fake executor (php -S serving canned 202s and status answers) with push notifications stubbed. It covered dispatch, success, three retries and give-up, a stale-attempt callback being ignored, retry counts resetting on the next turn, expiry followed by a late error (ignored) and a late success (delivered), cancel, never-dispatched expiry, adoption and listing. Real schema, real data, no lasting writes. Re-create such a harness whenever the lifecycle changes.

Sessions and resume

Continuing a thread sends only the new message plus the stored session id (--resume). If the session is gone ("No conversation found with session ID"), every retry with the same stale id fails identically. Clear the stored session id before retrying so the retry falls back to sending the full conversation; the executor also drops --resume for its own internal retries on a session error. Sessions are per working directory, so a post must keep the project it started in.

Diagnosing an empty failure

claude CLI exited with code 1: with nothing after the colon was the account's usage limit: in --output-format json mode the CLI prints that notice on stdout and leaves stderr empty. The real message was recoverable from the session transcript (~/.claude/projects/<dir>/*.jsonl, last assistant line). Always build error text from stderr, then stdout.

Liveness for users

A tap-to-check health badge calls GET /ai/health, which curls the executor's /health with short connect/total timeouts (3 s / 5 s) and always returns 200 with {up, latency_ms, queued, error}. A dead tunnel gives instant "down"; a suspended desktop with a listening forward gives "down" after 5 s; no answer from the API itself is a third state ("no reply").

Work that outlives the session (design, post #1867)

An agent that hits its session timeout detaches long work (a release build) and reports later with a follow-up. The job then reads "answered" while work is still running, and nothing records that it is. A "still working" indicator needs something real behind it: - Register the work. A wrapper (background.sh <post> "<label>" -- <command>) calls a signed endpoint with label, pid, start time and expected duration, runs the command detached, and in an EXIT trap posts the result (success or failure, with the exit code and log tail) and clears the marker. - A marker that lies is worse than none. Detached processes die when the executor restarts or the machine suspends, and then the trap never fires. So the wrapper heartbeats every ~2 min, and the existing expiry sweeper clears markers silent for ~10 min and posts "stopped reporting". The heartbeat also gives an honest elapsed time and room for a progress phase. - Make the indicator visibly different from "thinking" (the session itself running): a small pulsing "Still working: Release build · 12m" chip under the last response, a dot on the card. - It only works if the agent uses the wrapper, so make it the documented path in the system prompt; the executor cannot reliably detect processes that escaped with setsid.

Known gaps worth designing for

See also

Linked from

Sources: tldr memory (bug-ai-false-timeout-expire-cron, feature-ai-error-status, bug-ai-usage-limit-hold, completed-work, claude-service-sessions, feature-ai-cancel-status, feature-ai-health-badge, feature-ai-request-table), posts #1449, #1561, #1634, #1635, #1641, #1652, #1779, #1824, #1867