Skip to content

Tracking cycle: stop waiting on ghost Cloro tasks — cuts the nightly cycle from ~5h to ~1.5h #687

Closed

Description

@gkhngyk

Problem

The nightly cycle takes 5+ hours from cron start to the last pulse mail (mails landing 4-5.5h after the cron), and the dominant cost is waiting on tasks that will never arrive. Observed on a recent run: a large brand's ~1800 tasks were submitted, ~1790 results arrived within minutes-to-tens-of-minutes, and a handful of scraper tasks (all google-aio) never received a callback — they were still pending 6 hours later. Those ghosts burn two timers back to back:

  1. Worker drain waits the full no-progress stall window (60 min in prod via CLORO_STALL_POLL_LIMIT) before stamping the run.
  2. Pulse drain (waitForCloroDrain) then polls the same never-draining queue for its full 90-minute cap (DRAIN_MAX_WAIT_MS) before sending the mail.

With MAX_CONCURRENT_TRACKING = 2 (server/src/lib/job-runner.js#L23) each brand pair holds its slot for ~an hour, so wave completions land exactly hourly and late-queue brands start 3+ hours after the cron.

Key insight — the pulse wait is vestigial

Since the tracking-run ledger (#649 era), pulse KPI windows anchor to run stamps, not the clock (server/src/lib/pulse/metrics.js#L325-L349 — "the email can never disagree with the dashboard"). Results arriving after the stamp fall into the next window for mail and dashboard alike, so waiting 90 minutes changes nothing about the numbers — it only delays the mail. There is no mail/panel divergence risk in removing it.

Changes

  1. Pulse: make waitForCloroDrain ignore stale tasks. Filter the pending count to tasks younger than ~45-60 min (submitted_at); ghosts older than that will never drain and cleanupStalePendingTasks sweeps them next cycle anyway. Alternatively drop the wait entirely for stamp-anchored daily pulses — document why if so.
  2. Worker: ghost-aware early exit in the drain loop (server/src/workers/tracking-worker.js, drain section ~L277-L340). Keep waiting while results are flowing; exit early only when BOTH (a) no progress for N minutes (N well below the stall cap, e.g. ~15 min) AND (b) every remaining pending task is old (submitted 30+ min ago). Cloro's real burst gaps stay tolerated; only true ghosts stop costing an hour. The MIN_STAMP_RATIO 50% guard stays as the backstop against partial stamps.\n3. Concurrency: make it configurable. Replace the hardcoded MAX_CONCURRENT_TRACKING = 2 with TRACKING_CONCURRENCY env (default 2, documented in server/.env.example). Prod plan: raise to 3 after the wait fix ships, watch free -h / docker stats on the next cron, then settle at 3-4 (t3.small + swap headroom).\n\n### Expected effect\n\n- Wave duration drops from ~60 min to ~15-20 min → full cycle ~1.5h even at concurrency 2; under an hour at 3-4.\n- Pulse mails land minutes after each run's stamp instead of +90 min.\n- Accepted, already-true today: answers arriving after the stamp count toward the next day's window (mail and dashboard consistently).\n\n### Follow-up (separate)\n\nAsk the scraper provider whether "no result" tasks can emit an explicit failure callback — that would eliminate ghosts at the source.

Activity

  1. added
    enhancement
    on Aug 9, 2026
  2. self-assigned this
    on Aug 9, 2026
  3. gkhngyk commented on Aug 10, 2026

    @gkhngyk
    ContributorAuthor

    Field evidence: this also causes pulses to be dropped entirely, not just delayed

    On 2026-08-10 the largest brand on the instance got no pulse at all. The run itself was fine (completed 05:15 UTC, 1791 results), every eligibility check passed, and no row was ever written to sent_pulses. The server log shows why:

    "msg":"daily pulse generation failed"
    "message":"ai_visibility_aggregates failed: canceling statement due to statement timeout"
        at rpc (src/lib/pulse/metrics.js:50)
        at visibilityRate (src/lib/pulse/metrics.js:60)
        at computePulseMetrics (src/lib/pulse/metrics.js:370)
        at generatePulseForBrand (src/lib/pulse/engine.js:157)
    

    Measured on the same window with the database otherwise idle:

    • ai_visibility_aggregates for that brand and window: 526 ms — far under the 8s statement_timeout PostgREST's role carries
    • but it is a heavy statement: Buffers: shared hit=126238 (~1 GB touched) with temp read=791 written=793, i.e. it spills to disk because work_mem is 3500kB
    • that brand holds 41,124 of the table's 131,960 rows (table 737 MB)

    So the statement is not slow on its own — it becomes slow under concurrency, and the 90-minute drain is what manufactures that concurrency. Because every brand waits the same fixed 90 minutes, brands whose runs finished minutes apart all wake up in the same second:

    when brands pulsed simultaneously
    08-09 07:36 6 (incl. the 1791-result brand — passed, barely)
    08-10 05:45 5
    08-10 06:46 4 (the 1791-result brand failed)

    Each of those brands also fires several ai_visibility_aggregates calls in parallel (Promise.all in computePulseMetrics), so a wake-up wave puts ~20 heavy statements on the database at once. The largest brand is the one that crosses 8s and dies; the smaller ones in the same wave succeed. It passed one day and failed the next — classic edge-of-resource behaviour.

    This widens the scope slightly

    Point 1 below is already the issue's main change; 2 and 3 are what this incident adds:

    1. Remove the ghost-task wait (as specified above) — this also de-synchronises the wake-ups, which is the actual fix for the timeouts, not just for the delay.
    2. Run the pulse metric RPCs sequentially instead of Promise.all. Nobody is waiting on this job interactively, so the parallelism buys nothing and multiplies peak database load per brand.
    3. Don't let one timeout discard the whole pulse. Today the catch in generatePulseForBrand swallows the error and returns { error: true }, so the digest is simply lost until the next day's catch-up sweep. It should either retry once or leave the run unclaimed so the sweep picks it up the same cycle.

    Worth noting for whoever picks this up: raising statement_timeout would hide the symptom without addressing the load, and the brand will keep growing — the sequential + de-synchronised combination is the durable fix.

  4. added a commit that references this issue on Aug 10, 2026
    0608c01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions