Repository navigation
Tags
Tags
Free job locks left behind by pools that stopped without releasing th… …em (#12) * Free job locks left behind by pools that stopped without releasing them Two fixes for a lock that stays taken after its job finished, which stops a MaxConcurrency job from ever running again. Worker: removeJobFromInProgress removed the job from the in-progress list with LREM of job.rawJSON. For a unique job keyed with ...ByKey, processJob swaps in the job stored under the unique key, whose bytes differ from the list entry (the scheduler re-encodes the job, and a duplicate enqueue overwrites the key with a new job). The LREM then matched nothing and the entry stayed. The job now keeps the bytes it was fetched with and removes those. Dead pool reaper: if the lock release fails and the pool then stops gracefully, the pool leaves worker_pools while its lock_info field still counts a held lock. findDeadPools only walks worker_pools, so nothing released it. reap() now also sweeps lock_info of the current job types for pools that are not in worker_pools and have no fresh heartbeat. A pool is reaped only when it was such an orphan in the previous pass too. A Lua script re-checks both conditions, then frees the lock: it never lowers the lock below what pools in worker_pools hold, never raises it for a positive count, and clamps at 0. It never touches in-progress lists or job queues. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NT6Ytc6ibavuP95LjW7MPb * Test the live-pool floor inputs and name the job and pool in sweep errors Script test rows: a live pool with a negative count does not lower the floor, live counts are summed, and a heartbeat exactly at the cutoff is stale. Sweep errors now name the job type and pool id, and the summary line goes through a logInfo helper next to logError. reverted redis.go:272 (held > 0): TestReapOrphanedLockScript fails (negative_live_count_does_not_lower_the_floor) reverted redis.go:273 (sum to last value): TestReapOrphanedLockScript fails (live_counts_are_summed) reverted redis.go:243 (> to >=): TestReapOrphanedLockScript fails (heartbeat_at_the_cutoff_is_stale) dead_pool_reaper.go:199-226 and log.go: no behaviour change: log text and bookkeeping only (one Receive per sent script, same order) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NT6Ytc6ibavuP95LjW7MPb * Test the unchanged-lock, zero-count and registered-pool guards A missing lock key stays missing when the script runs. A zero count does not read the other pools' counts. A pool still in worker_pools is never counted toward the two-pass confirmation, so it waits two passes after it leaves. The sweep uses the reaper's deadTime, and the script returns 0 once the lock info field is gone. The heartbeat and lock_info read errors now name the pool id and job type. reverted redis.go:288 (newLock ~= lock): TestDeadPoolReaperOrphanedLockCounts fails (missing_lock_key) reverted redis.go:263 (count ~= 0): TestReapOrphanedLockScript fails (zero_count_does_not_read_other_counts) reverted dead_pool_reaper.go:158 (livePools skip): TestDeadPoolReaperOrphanedLockRegisteredPoolNotCounted fails reverted dead_pool_reaper.go:170 (r.deadTime to deadTime): TestDeadPoolReaperOrphanedLockUsesReaperDeadTime fails dead_pool_reaper.go:154,184: no behaviour change: log text only Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NT6Ytc6ibavuP95LjW7MPb --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Fix concurrent map iteration/write crash in observer.writeStatus (#11) * Fix concurrent map iteration/write crash in observer.writeStatus observeStarted() stored the caller's arguments map by reference instead of copying it. The observer's own background goroutine later marshals that same map (writeStatus -> json.Marshal), potentially seconds after the job started -- concurrently with whatever the caller does with its own reference to the same map in the meantime. Unsynchronized concurrent map access is a Go fatal error, not a recoverable panic: it kills the whole worker process immediately. This crashed outdoorsy/api's production workers 8 times over 9 days with "fatal error: concurrent map iteration and map write" at exactly this call site. Each crash killed a worker mid-job, which triggered the dead-pool-reaper to requeue the in-flight job onto another pod -- the same downstream duplicate-execution symptom investigated and partly fixed in the periodic-enqueuer race (#10), but via a separate trigger this PR addresses independently. Fix: copyArgs() takes a shallow copy at the observer boundary so it never shares the map with the caller again. Shallow, not deep -- proportionate given Args is a debug-only payload of JSON-unmarshaled scalars/containers, not a value with live nested aliases elsewhere; documented on copyArgs. Added TestObserverDoesNotShareArgumentsMapWithCaller: mutates the original map concurrently with repeated drain() calls (which synchronously trigger writeStatus's json.Marshal) under -race. Verified it fails with a data race matching the exact production crash's stack trace when reverted to the old aliasing behavior, and passes cleanly (5/5 runs) with the fix. * Add tests for copyArgs nil and shallow-copy semantics Addresses review feedback on PR #11 (non-blocking, but this is the production-crash fix -- no room for gaps): copyArgs had no direct test for the nil case or for what "shallow" actually means in practice. - TestCopyArgsNil: copyArgs(nil) returns nil; observeStarted(..., nil) round-trips through writeStatus identically to the pre-fix behavior (empty args string), matching writeStatus's existing nil/empty check. - TestCopyArgsIsShallowNotDeep: asserts both halves explicitly -- top-level keys are independent between original and copy (what the fix guarantees), and a nested map value is the same underlying object in both (the accepted, documented limitation) -- so a future change to copyArgs's semantics shows up here as a deliberate, visible diff instead of silent drift. Verified both catch real breakage, not just passing vacuously: reverted copyArgs to an identity no-op (return args) and confirmed TestCopyArgsIsShallowNotDeep fails with the expected top-level-aliasing errors; restored the real implementation and confirmed both pass, 3/3 runs under -race alongside the rest of the observer suite. * Use stdlib maps.Clone instead of a hand-rolled copy loop Per review feedback: no reason to hand-roll the shallow-copy loop when the standard library's maps.Clone (go.mod already pins go 1.22.0) does exactly this -- same nil-in/nil-out and shallow-copy semantics the fix needs. copyArgs kept as a thin wrapper so the shallow-vs-deep rationale stays documented at the one call site, and TestCopyArgsNil / TestCopyArgsIsShallowNotDeep keep working unchanged (maps.Clone has the identical contract those tests assert). Verified: go build clean, gofmt clean, full observer suite 3/3 under -race, full package suite green.
Fix race and unit bug in periodic-enqueuer dedup check (#10) * Fix race and unit bug in periodic-enqueuer dedup check shouldEnqueue() did a plain GET, branched on it in Go, then only SET the "last enqueued" timestamp at the end of enqueue() -- a check-then-act race across worker pool processes sharing a namespace. It also compared epoch seconds against periodicEnqueuerSleep/time.Minute (a bare 2), off by a factor of 60: the intended 2-minute dedup window was actually about 2 seconds, so the gate almost never blocked a concurrent caller. Replace both with a single Lua script that reads, compares, and claims the window atomically, so only one process per window proceeds to enqueue(). This is suspected to be a contributing factor in production worker pods independently over-firing several daily cron jobs (seen firing 2x-288x instead of once on some days). * Add test coverage for shouldEnqueue()'s fail-open error path The GET-to-Lua-script switch left the Redis-error branch (fail open, return true) untested -- go tool cover showed 0% on that block. Exercise it directly against an unreachable Redis pool, same pattern worker_test.go already uses for connection-error testing. * Add CI: run go build/test on every PR This repo had no CI at all -- no GitHub Actions, no branch protection, nothing enforcing that tests pass before merge. Tests need a live Redis on :6379 (hardcoded via newTestPool), so spin one up as a service container. * Revert: remove CI workflow Not adding CI to this public repo without more thought given to what that exposes. * Release the enqueue claim on failure, don't hold it for the full window enqueue() only ever schedules occurrences forward from the current time. Claiming the window before enqueue() runs (this PR's earlier commit) means a partial failure -- one bad ZADD, a serialize error -- left the claim held for the rest of the window with nothing scheduled for that pass. The next successful attempt starts its forward scan from its own later "now", so anything that should have fired in the gap is skipped permanently, not just delayed. Worse for any job scheduled more often than the window itself. Extract the shouldEnqueue+enqueue pairing into tryEnqueue(), and have it DEL the claim key on enqueue() failure so the next tick -- on any process -- can retry immediately instead of waiting out the window. Added a regression test that forces a real ZADD failure (via a wrong-type key, over a live connection) and confirms the claim is released; verified it fails without the DEL and passes with it. * Make releaseClaim() a compare-and-delete, not an unconditional DEL If this process's own claim expires (severe stall during enqueue()) and another process re-claims the window in the meantime, an unconditional DEL on failure would delete that newer, valid claim and momentarily reopen the exact race this PR closes. shouldEnqueue() now records the timestamp it claimed with; releaseClaim only deletes the key if it still holds that exact value, via a Lua script (redisLuaReleaseClaim) so the compare-and-delete is atomic. Added a regression test that plants a newer claim before calling releaseClaim() and asserts it survives; verified it fails against an unconditional DEL and passes with the compare-and-delete.