queue-chaos 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
qadvice.py ADDED
@@ -0,0 +1,54 @@
1
+ """One-line config advice for `queue-chaos check`.
2
+
3
+ Only things measured in this repo are here; every rule names where (FINDINGS.md section or README).
4
+ Rules are matched on (preset, fault, anomaly, observed settings). If a case is not measured, there is no rule.
5
+ """
6
+
7
+ # anomaly names are the ones check uses: lost, dup_unexplained, concurrent, dup_complete
8
+ RULES = [
9
+ dict(preset="celery", faults=("kill",), anomaly="lost",
10
+ when=lambda s, b: not s.get("task_acks_late"),
11
+ text="Set task_acks_late=True and task_reject_on_worker_lost=True. With the defaults the message is acked "
12
+ "when the task starts, so a killed worker loses its tasks (FINDINGS 2026-11-25, Celery 5.4.0).",
13
+ source="FINDINGS.md 2026-11-25"),
14
+ dict(preset="celery", faults=("kill",), anomaly="lost",
15
+ when=lambda s, b: bool(s.get("task_acks_late")) and b == "redis",
16
+ text="acks_late is on, so this may be a late redelivery, not a loss: kombu 5.6.2 sweeps unacked messages "
17
+ "about every 100 s whatever visibility_timeout is. Re-run with a longer --drain before concluding.",
18
+ source="FINDINGS.md 2026-11-26 (Celery restore delay)"),
19
+ dict(preset="celery", faults=("broker-restart",), anomaly="lost",
20
+ when=lambda s, b: b == "redis" and s.get("kombu") == "5.7.0",
21
+ text="kombu 5.7.0: the worker exits when the Redis broker restarts (celery/celery#11054), so queued jobs "
22
+ "are never processed. Fixed by kombu PR #2839 (not in a release yet); pin kombu<5.7.0 until then. "
23
+ "Measured: 3 of 6 broker-restart seeds lost jobs on 5.7.0, 0 of 7 runs with the fix "
24
+ "(experiments/historical/D12b-results.md, row 18).",
25
+ source="D12b-results.md row 18; celery#11054"),
26
+ # rq "lost on kill without Retry -> enqueue with retry=Retry(max=...)" is NOT here: the kill fault did not lose
27
+ # any rq job in this repo's runs (rq's work-horse runs in its own process group and finishes the job), so the
28
+ # claim is not measured. Add it once a run shows it.
29
+ ]
30
+
31
+ # Warnings that depend only on the configuration, shown even when no anomaly was found.
32
+ CONFIG_RULES = [
33
+ dict(preset="celery",
34
+ when=lambda s, b: (b == "redis" and bool(s.get("task_acks_late"))
35
+ and isinstance(s.get("visibility_timeout"), (int, float))
36
+ and s["visibility_timeout"] < 10),
37
+ text="visibility_timeout is under 10 s with acks_late on Redis: a 2 s timeout gave 12-22% duplicate runs "
38
+ "on broker restart, 10 s gave 0.1% (FINDINGS 2026-11-26).",
39
+ source="FINDINGS.md 2026-11-26"),
40
+ ]
41
+
42
+
43
+ def advise(preset, fault, anomalies, settings, broker):
44
+ """Advice lines for one fault. `anomalies` is the set of anomaly names seen for it."""
45
+ out = []
46
+ for r in RULES:
47
+ if (r["preset"] == preset and fault in r["faults"] and r["anomaly"] in anomalies
48
+ and r["when"](settings, broker)):
49
+ out.append(r["text"])
50
+ return out
51
+
52
+
53
+ def config_warnings(preset, settings, broker):
54
+ return [r["text"] for r in CONFIG_RULES if r["preset"] == preset and r["when"](settings, broker)]
qcheck.py ADDED
@@ -0,0 +1,249 @@
1
+ """`queue-chaos check`: run the harness against your own Celery / rq setup and print a verdict per fault.
2
+
3
+ Each run is a normal chaos.py run (one subprocess per run), so results are the same kind the study uses; only
4
+ the defaults are shorter. See docs/PRESETS.md.
5
+
6
+ Exit codes: 0 clean, 1 confident anomaly (lost / dup_unexplained / concurrent > 0), 2 could not run
7
+ (bad arguments, app does not import, or a run completed nothing).
8
+ """
9
+ import argparse, glob, json, os, subprocess, sys, time
10
+ from xml.sax.saxutils import escape, quoteattr
11
+
12
+ import qadvice
13
+
14
+ HERE = os.path.dirname(os.path.abspath(__file__))
15
+ FAULTS_OK = ("kill", "term", "pause", "broker-restart", "partition")
16
+ ANOMALIES = ("lost", "dup_unexplained", "concurrent") # these fail the check
17
+ PRESET_BROKERS = {"celery": ("redis", "rabbitmq"), "rq": ("redis",)}
18
+
19
+
20
+ def parse_args(argv):
21
+ ap = argparse.ArgumentParser(prog="queue-chaos check", description=__doc__.split("\n\n")[0])
22
+ ap.add_argument("preset", choices=sorted(PRESET_BROKERS))
23
+ ap.add_argument("--app", help="module:attr of your Celery app (rq: optional Queue or Worker subclass)")
24
+ ap.add_argument("--broker", choices=["redis", "rabbitmq"], default="redis")
25
+ ap.add_argument("--faults", default="kill,term,broker-restart",
26
+ help="comma list from: " + ",".join(FAULTS_OK))
27
+ ap.add_argument("--seeds", type=int, default=3)
28
+ ap.add_argument("--quick", action="store_true", help="one seed per fault")
29
+ ap.add_argument("--env", action="append", default=[], metavar="KEY=VAL",
30
+ help="environment variable for your app (repeatable), e.g. DJANGO_SETTINGS_MODULE=proj.settings")
31
+ ap.add_argument("--pre-import", default="", metavar="MODULE", help="import before the app (comma list); "
32
+ "'django' also runs django.setup()")
33
+ ap.add_argument("--json", metavar="PATH")
34
+ ap.add_argument("--junit", metavar="PATH")
35
+ ap.add_argument("--retry", type=int, default=0, help="rq only: Retry(max=N) on every job")
36
+ ap.add_argument("--job-timeout", type=int, default=0, help="rq only: job_timeout in seconds")
37
+ ap.add_argument("--jobs", type=int, default=100)
38
+ ap.add_argument("--drain", type=float, default=None, help="max seconds to wait for jobs after the faults "
39
+ "(default 60, rq 90)")
40
+ ap.add_argument("--out", default="queue-chaos-results", help="directory for per-run files and worker stderr")
41
+ a = ap.parse_args(argv)
42
+ a.faults = [f for f in a.faults.split(",") if f]
43
+ bad = [f for f in a.faults if f not in FAULTS_OK]
44
+ if bad:
45
+ ap.error(f"unknown fault(s) {bad}; choose from {list(FAULTS_OK)}")
46
+ if a.broker not in PRESET_BROKERS[a.preset]:
47
+ ap.error(f"preset {a.preset} supports --broker {'/'.join(PRESET_BROKERS[a.preset])}")
48
+ if a.preset == "celery" and not a.app:
49
+ ap.error("the celery preset needs --app module:attr")
50
+ if a.preset != "rq" and (a.retry or a.job_timeout):
51
+ ap.error("--retry and --job-timeout are rq flags")
52
+ for kv in a.env:
53
+ if "=" not in kv:
54
+ ap.error(f"--env expects KEY=VAL, got {kv!r}")
55
+ if a.quick:
56
+ a.seeds = 1
57
+ if a.seeds < 1:
58
+ ap.error("--seeds must be at least 1")
59
+ if a.drain is None:
60
+ # Celery on Redis with acks_late: kombu restores unacked messages on a ~100 s sweep, so a shorter drain
61
+ # reports late redeliveries as lost (FINDINGS 2026-11-26; seen again in the 2026-12-06 smoke runs).
62
+ a.drain = 90.0 if a.preset == "rq" else 150.0 if (a.preset == "celery" and a.broker == "redis") else 60.0
63
+ return a
64
+
65
+
66
+ def run_env(a):
67
+ env = dict(os.environ, QC_PYTHON=sys.executable)
68
+ if a.app:
69
+ env["QC_APP"] = a.app
70
+ if a.pre_import:
71
+ env["QC_PRE_IMPORT"] = a.pre_import
72
+ if a.retry:
73
+ env["QC_RQ_RETRY"] = str(a.retry)
74
+ if a.job_timeout:
75
+ env["QC_RQ_JOB_TIMEOUT"] = str(a.job_timeout)
76
+ for kv in a.env:
77
+ k, _, v = kv.partition("=")
78
+ env[k] = v
79
+ return env
80
+
81
+
82
+ def adapter_path(preset):
83
+ path = os.path.join(HERE, "queue_chaos_presets", preset, "adapter")
84
+ if not os.access(path, os.X_OK): # wheels/sdists can drop the exec bit on package data
85
+ try:
86
+ os.chmod(path, 0o755)
87
+ except OSError:
88
+ import tempfile
89
+ d = tempfile.mkdtemp(prefix="qc-preset-")
90
+ w = os.path.join(d, "adapter")
91
+ with open(w, "w") as f:
92
+ f.write('#!/bin/sh\n[ "$(uname)" = Darwin ] && export FORKED_BY_MULTIPROCESSING=1\n'
93
+ 'exec "${QC_PYTHON:-python3}" "%s" "$@"\n' % os.path.join(os.path.dirname(path), "adapter.py"))
94
+ os.chmod(w, 0o755)
95
+ path = w
96
+ return path
97
+
98
+
99
+ def probe(a, env):
100
+ """Import the user's app once, in the adapter's own process, and read back the settings that matter."""
101
+ url = {"redis": "redis://127.0.0.1:1", "rabbitmq": "amqp://guest:guest@127.0.0.1:1//"}[a.broker]
102
+ p = subprocess.run([adapter_path(a.preset), "probe"], env=dict(env, CHAOS_URL=url),
103
+ capture_output=True, text=True)
104
+ for line in p.stdout.splitlines():
105
+ if line.startswith("QC_PROBE "):
106
+ return json.loads(line[len("QC_PROBE "):])
107
+ sys.stderr.write(p.stderr[-2000:] + "\n")
108
+ raise SystemExit(f"could not load your app ({a.app}); fix the error above (rc={p.returncode})")
109
+
110
+
111
+ def one_run(a, env, fault, seed):
112
+ out = os.path.join(a.out, f"{fault}-seed{seed}")
113
+ cmd = [sys.executable, os.path.join(HERE, "chaos.py"), "--adapter", adapter_path(a.preset),
114
+ "--backend", a.broker, "--fault", fault, "--seed", str(seed), "--out", out,
115
+ "--jobs", str(a.jobs), "--work-ms", "200", "--workers", "2", "--concurrency", "2",
116
+ "--drain", str(a.drain), "--fault-window", "10"]
117
+ if fault != "none":
118
+ cmd += ["--faults", "2"]
119
+ t0 = time.time()
120
+ p = subprocess.run(cmd, env=env, capture_output=True, text=True)
121
+ row = dict(fault=fault, seed=seed, rc=p.returncode, secs=round(time.time() - t0), out=out)
122
+ files = sorted(glob.glob(os.path.join(out, "*.json")))
123
+ if p.returncode == 2 or not files:
124
+ row.update(valid=False, note=(p.stdout.strip().splitlines() or p.stderr.strip().splitlines() or [""])[-1])
125
+ return row
126
+ res = json.load(open(files[-1]))["result"]
127
+ row.update(valid=True, completed=res["completed_once"], faults_injected=json.load(open(files[-1]))["faults_injected"],
128
+ **{k: len(res[k]) for k in ("lost", "dup_complete", "dup_unexplained", "concurrent", "redelivered")})
129
+ return row
130
+
131
+
132
+ def summarize(a, settings, rows):
133
+ """Per-fault verdicts from the raw run rows."""
134
+ verdicts = []
135
+ for fault in ["none"] + a.faults:
136
+ rs = [r for r in rows if r["fault"] == fault]
137
+ if not rs:
138
+ continue
139
+ v = dict(fault=fault, seeds=len(rs), runs=rs)
140
+ if any(not r["valid"] for r in rs):
141
+ v.update(status="INVALID", anomalies=[], **{k: None for k in
142
+ ("lost", "dup_complete", "dup_unexplained", "concurrent", "redelivered")})
143
+ else:
144
+ for k in ("lost", "dup_complete", "dup_unexplained", "concurrent", "redelivered"):
145
+ v[k] = sum(r[k] for r in rs)
146
+ v["anomalies"] = [k for k in ANOMALIES if v[k] > 0]
147
+ v["status"] = "ANOMALY" if v["anomalies"] else "ok"
148
+ v["advice"] = qadvice.advise(a.preset, fault, set(v["anomalies"]), settings, a.broker)
149
+ verdicts.append(v)
150
+ return verdicts
151
+
152
+
153
+ def exit_code(verdicts):
154
+ if any(v["anomalies"] for v in verdicts):
155
+ return 1
156
+ if any(v["status"] == "INVALID" for v in verdicts):
157
+ return 2
158
+ return 0
159
+
160
+
161
+ def render_table(verdicts):
162
+ cols = ["fault", "seeds", "status", "lost", "dup_unexpl", "concurrent", "dup_complete", "redelivered"]
163
+ rows = [[v["fault"], v["seeds"], v["status"], v["lost"], v["dup_unexplained"], v["concurrent"],
164
+ v["dup_complete"], v["redelivered"]] for v in verdicts]
165
+ rows = [["-" if c is None else str(c) for c in r] for r in rows]
166
+ w = [max(len(c), *(len(r[i]) for r in rows)) for i, c in enumerate(cols)]
167
+ line = lambda r: " ".join(x.ljust(w[i]) for i, x in enumerate(r))
168
+ return "\n".join([line(cols), line(["-" * n for n in w])] + [line(r) for r in rows])
169
+
170
+
171
+ def render_markdown(a, settings, verdicts, warnings, code):
172
+ md = [f"## queue-chaos check: {a.preset} on {a.broker}", "",
173
+ f"Result: **{'FAIL' if code == 1 else 'could not run' if code == 2 else 'pass'}**. "
174
+ "Failing columns are lost, dup_unexplained and concurrent; dup_complete and redelivered are expected "
175
+ "under at-least-once and only reported.", "",
176
+ "| fault | seeds | status | lost | dup_unexplained | concurrent | dup_complete | redelivered |",
177
+ "|---|---|---|---|---|---|---|---|"]
178
+ for v in verdicts:
179
+ md.append("| " + " | ".join("-" if x is None else str(x) for x in (
180
+ v["fault"], v["seeds"], v["status"], v["lost"], v["dup_unexplained"], v["concurrent"],
181
+ v["dup_complete"], v["redelivered"])) + " |")
182
+ md += ["", "Settings read from your app: `" + json.dumps(settings, sort_keys=True) + "`"]
183
+ notes = [(v["fault"], t) for v in verdicts for t in v["advice"]]
184
+ if notes or warnings:
185
+ md += ["", "### Advice"]
186
+ md += [f"- {w}" for w in warnings] + [f"- **{f}**: {t}" for f, t in notes]
187
+ return "\n".join(md) + "\n"
188
+
189
+
190
+ def render_junit(a, verdicts, secs):
191
+ fails = sum(1 for v in verdicts if v["anomalies"])
192
+ errs = sum(1 for v in verdicts if v["status"] == "INVALID")
193
+ x = ['<?xml version="1.0" encoding="UTF-8"?>',
194
+ f'<testsuite name={quoteattr(f"queue-chaos {a.preset} {a.broker}")} tests="{len(verdicts)}" '
195
+ f'failures="{fails}" errors="{errs}" time="{secs}">']
196
+ for v in verdicts:
197
+ t = sum(r["secs"] for r in v["runs"])
198
+ x.append(f' <testcase classname={quoteattr("queue-chaos." + a.preset)} name={quoteattr(v["fault"])} time="{t}">')
199
+ if v["status"] == "INVALID":
200
+ notes = "; ".join(r.get("note", "") for r in v["runs"] if not r["valid"])
201
+ x.append(f' <error message={quoteattr("run completed nothing: " + notes)}/>')
202
+ elif v["anomalies"]:
203
+ msg = ", ".join(f"{k}={v[k]}" for k in v["anomalies"])
204
+ body = "\n".join(v["advice"])
205
+ x.append(f' <failure message={quoteattr(msg)}>{escape(body)}</failure>')
206
+ x.append(" </testcase>")
207
+ x.append("</testsuite>")
208
+ return "\n".join(x) + "\n"
209
+
210
+
211
+ def main(argv):
212
+ a = parse_args(argv)
213
+ env = run_env(a)
214
+ settings = probe(a, env)
215
+ print(f"queue-chaos check: {a.preset} on {a.broker}; settings: {json.dumps(settings, sort_keys=True)}")
216
+ t0 = time.time()
217
+ rows = []
218
+ plan = [("none", 1)] + [(f, s) for f in a.faults for s in range(1, a.seeds + 1)]
219
+ for i, (fault, seed) in enumerate(plan, 1):
220
+ r = one_run(a, env, fault, seed)
221
+ rows.append(r)
222
+ if r["valid"]:
223
+ print(f"[{i}/{len(plan)}] {fault} seed {seed}: completed={r['completed']} lost={r['lost']} "
224
+ f"dup_unexplained={r['dup_unexplained']} concurrent={r['concurrent']} "
225
+ f"dup_complete={r['dup_complete']} ({r['secs']}s)", flush=True)
226
+ else:
227
+ print(f"[{i}/{len(plan)}] {fault} seed {seed}: INVALID, {r['note']} (worker stderr in {r['out']})", flush=True)
228
+ verdicts = summarize(a, settings, rows)
229
+ warnings = qadvice.config_warnings(a.preset, settings, a.broker)
230
+ code = exit_code(verdicts)
231
+ secs = round(time.time() - t0)
232
+ print("\n" + render_table(verdicts))
233
+ for w in warnings:
234
+ print("warning: " + w)
235
+ for v in verdicts:
236
+ for t in v["advice"]:
237
+ print(f"advice ({v['fault']}): {t}")
238
+ print(f"\n{'FAIL' if code == 1 else 'could not run' if code == 2 else 'pass'} in {secs}s (exit {code})")
239
+ if os.environ.get("GITHUB_STEP_SUMMARY"):
240
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f:
241
+ f.write(render_markdown(a, settings, verdicts, warnings, code))
242
+ if a.json:
243
+ with open(a.json, "w") as f:
244
+ json.dump(dict(preset=a.preset, broker=a.broker, settings=settings, exit_code=code,
245
+ seconds=secs, warnings=warnings, faults=verdicts), f, indent=1)
246
+ if a.junit:
247
+ with open(a.junit, "w") as f:
248
+ f.write(render_junit(a, verdicts, secs))
249
+ return code
@@ -0,0 +1,251 @@
1
+ Metadata-Version: 2.4
2
+ Name: queue-chaos
3
+ Version: 1.1.0
4
+ Summary: Fault-injection checker for background job queues (lost, duplicate and concurrent job execution)
5
+ License: MIT OR Apache-2.0
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE-APACHE
9
+ License-File: LICENSE-MIT
10
+ Dynamic: license-file
11
+
12
+ # queue-chaos
13
+
14
+ [![selftest](https://github.com/biplabku/queue-chaos/actions/workflows/selftest.yml/badge.svg)](https://github.com/biplabku/queue-chaos/actions/workflows/selftest.yml)
15
+ [![pypi](https://img.shields.io/pypi/v/queue-chaos?color=3776AB)](https://pypi.org/project/queue-chaos/)
16
+ ![python](https://img.shields.io/badge/python-3.8%2B-3776AB?logo=python&logoColor=white)
17
+ ![deps](https://img.shields.io/badge/orchestrator%20deps-stdlib%20only-success)
18
+ ![queues](https://img.shields.io/badge/queues-19-orange)
19
+ ![license](https://img.shields.io/badge/license-MIT%20%7C%20Apache--2.0-blue)
20
+
21
+ Fault-injection checker for background job queues. It runs your queue's real workers against a real broker in
22
+ Docker, breaks things on purpose (kills workers, restarts Redis/Postgres, cuts the network, fills the disk, skews
23
+ the clock...) and then checks every single job: did it run? did it run twice? did two workers run it at the same time?
24
+
25
+ **Test your own Celery or RQ app in one command** (no glue code; it keeps your settings and swaps in a throwaway broker):
26
+
27
+ ```bash
28
+ pip install queue-chaos
29
+ queue-chaos check celery --app proj.celery:app --quick
30
+ ```
31
+
32
+ ![queue-chaos check: default Celery settings lose jobs on a worker kill; acks_late + reject_on_worker_lost fixes it](https://raw.githubusercontent.com/biplabku/queue-chaos/main/docs/img/demo.gif)
33
+
34
+ In CI it's one step ([action](action.yml), [presets](docs/PRESETS.md)):
35
+
36
+ ```yaml
37
+ - uses: biplabku/queue-chaos@v1.1.0
38
+ with: { preset: celery, app: proj.celery:app, quick: "true" }
39
+ ```
40
+
41
+ For any other queue, write a small adapter (below); 19 are included to copy from.
42
+
43
+ ```text
44
+ $ queue-chaos --adapter adapters/sidekiq/adapter --backend redis --fault kill \
45
+ --rate 20 --faults 3 --fault-window 30 --drain 150 --stuck-ms 10000 --seed 3
46
+ redis-kill-seed3-1795924693: jobs=600 faults=3 completed_once=589 lost=11 dup_complete=0 dup_unexplained=0 concurrent=0 lease_overlap=0 redelivered=0 worker_exits=0
47
+ ```
48
+
49
+ That one says Sidekiq (OSS, BasicFetch) lost 11 of 600 jobs when 3 workers were SIGKILLed, which is
50
+ [documented](https://github.com/sidekiq/sidekiq/wiki/Reliability) behaviour. Other runs found real bugs; see
51
+ [upstream](#bugs-found-so-far).
52
+
53
+ ## How it works
54
+
55
+ ```mermaid
56
+ flowchart LR
57
+ O["queue-chaos<br/>(orchestrator)"] -- "enqueue 1 600 300" --> A1["adapter<br/>enqueue"]
58
+ O -- "spawn N x work" --> W["adapter workers<br/>(your queue's real worker code)"]
59
+ A1 --> B[("broker in Docker<br/>Redis / Postgres / Mongo / Faktory")]
60
+ W <--> B
61
+ F{{"fault injector<br/>kill · pause · term · restart<br/>partition · disk full · clock · cmdhold"}} -. breaks .-> W
62
+ F -. breaks .-> B
63
+ W -- "START / END lines" --> L["event log<br/>.events.tsv"]
64
+ L --> C["checker"] --> V["verdict<br/>.json + exit code"]
65
+ style O fill:#4f46e5,color:#fff
66
+ style F fill:#dc2626,color:#fff
67
+ style C fill:#059669,color:#fff
68
+ style V fill:#059669,color:#fff
69
+ style B fill:#f59e0b,color:#000
70
+ ```
71
+
72
+ An adapter is a small program (any language) that speaks a line protocol: `enqueue` some jobs, or `work` forever
73
+ and print `START`/`END` for each job. queue-chaos never talks to your queue directly, so anything with a
74
+ worker process can be tested.
75
+
76
+ ## Quick start
77
+
78
+ Needs Docker and Python 3.8+.
79
+
80
+ ```bash
81
+ pip install queue-chaos # gives the queue-chaos command
82
+ git clone https://github.com/biplabku/queue-chaos && cd queue-chaos
83
+
84
+ # set up one adapter (RQ here), then run a baseline and a fault
85
+ python3 -m venv adapters/rq/.venv && adapters/rq/.venv/bin/pip install rq redis
86
+ queue-chaos --adapter adapters/rq/adapter --backend redis --fault none
87
+ queue-chaos --adapter adapters/rq/adapter --backend redis --fault kill --seed 1
88
+ ```
89
+
90
+ Exit code is `1` if any job was lost or ran concurrently, so it drops into CI as is.
91
+ More recipes: **[docs/EXAMPLES.md](docs/EXAMPLES.md)**. Writing an adapter for your own queue:
92
+ **[docs/QUICKSTART.md](docs/QUICKSTART.md)**.
93
+
94
+ ## Test your own app (presets)
95
+
96
+ For Celery and rq you do not have to write an adapter. Point `check` at your app; it runs a no-fault baseline and
97
+ each fault with a few seeds against a throwaway broker container and prints a verdict per fault (about 5 minutes).
98
+ Install queue-chaos in the same environment as your app (Celery or rq and their broker client must be importable).
99
+
100
+ ```bash
101
+ queue-chaos check celery --app myproj.celery:app --quick # 1 seed per fault
102
+ queue-chaos check celery --app myproj.celery:app --broker rabbitmq --faults kill,term,broker-restart --seeds 3
103
+ queue-chaos check celery --app myproj.celery:app --env DJANGO_SETTINGS_MODULE=myproj.settings --pre-import django
104
+ queue-chaos check rq --app jobs:queue --retry 3 --job-timeout 60 --json out.json --junit out.xml
105
+ ```
106
+
107
+ Your own settings (acks_late, prefetch, visibility_timeout, ...) are kept; only the broker URL is replaced.
108
+ Exit code `1` means a lost, unexplained-duplicate or concurrent job; plain duplicates are reported, not failed.
109
+ Try it on [`examples/celery-app`](examples/celery-app) and [`examples/rq-app`](examples/rq-app).
110
+ Flags and details: **[docs/PRESETS.md](docs/PRESETS.md)**.
111
+
112
+ ## Faults
113
+
114
+ | `--fault` | What happens | Useful flags |
115
+ |---|---|---|
116
+ | `none` | baseline, must report zero problems | |
117
+ | `kill` | SIGKILL a random worker, then restart it | `--fault-every`, `--faults` |
118
+ | `term` | SIGTERM (graceful shutdown) with a deadline | `--grace-s`, `--term-scope group\|main` (whole process group, like systemd; or main process only, like `docker stop`) |
119
+ | `pause` | SIGSTOP a worker longer than its lease, then SIGCONT | `--pause-s`, `--stuck-ms` |
120
+ | `broker-restart` | `docker restart` the broker container | |
121
+ | `partition` | cut workers off from the broker for a while | `--partition-s` |
122
+ | `diskfull` | fill the Postgres data dir (tmpfs) | `--disk-mb`, `--diskfull-s` |
123
+ | `clockskew` / `clockjump` | shift the broker's clock (libfaketime) | `--skew --skew-s` |
124
+ | `cmdhold` | delay chosen Redis commands through a RESP proxy | `--hold 'BRPOP:3000'`, `--discover` |
125
+ | `mix` | random mix of the above, seeded | `--mix kill,pause,broker-restart` |
126
+
127
+ Add `--phase start` or `--phase end` to `kill`, `term` or `pause` to fire each fault on the worker that just printed
128
+ the next `START` (mid-job) or `END` (handler done, ack not written yet) instead of a random worker. That's where
129
+ lost acks and unfinished shutdown writes hide.
130
+
131
+ Poison jobs (a job that crashes its worker every time) are switched on in the adapter with
132
+ `CHAOS_POISON_EVERY=50 CHAOS_POISON=crash`.
133
+
134
+ ## What is checked
135
+
136
+ | Result | Meaning | Fails the run? |
137
+ |---|---|---|
138
+ | `lost` | job never completed | ❌ yes |
139
+ | `concurrent` | two executions overlapped while both workers were alive | ❌ yes |
140
+ | `dup_unexplained` | completed twice and nothing happened to the first worker | ⚠️ investigate (fails the Action) |
141
+ | `dup_complete` | completed more than once | ℹ️ allowed under at-least-once |
142
+ | `lease_overlap` | overlap because a paused worker outlived its lease | ℹ️ inherent to leases |
143
+ | `redelivered` | re-run after its worker was killed | ✅ expected |
144
+ | `lost_by_contract` | with `--contract at-most-once`: started on a worker that was then killed or exited, never completed (the loss the queue documents) | ℹ️ allowed by the contract |
145
+
146
+ Tell the checker your queue's documented guarantee with `--contract at-most-once` (default `at-least-once`).
147
+ Only jobs that **started** on a worker that then died move to `lost_by_contract`; jobs that never started stay `lost`.
148
+ The guarantees used in the study, with the doc quotes, are in [docs/contracts.json](docs/contracts.json).
149
+
150
+ ### How duplicates are classified
151
+
152
+ Every completed run of a job is one `START` ... `END` pair in the event log. A job with two or more `END`s is a
153
+ `dup_complete`. Under at-least-once delivery that's allowed, so on its own it never fails a run.
154
+
155
+ A duplicate is **explained** (stays only in `dup_complete`) when, for each pair of consecutive completed runs, at least
156
+ one of these happened between the first run's `START` and the second run's `START`:
157
+
158
+ - the first run's worker was killed, exited or paused (its ack may never have reached the broker);
159
+ - a broker-side event: restart, partition start/end, disk full/free, clock skew/jump;
160
+ - the second run's worker was paused in that window or within one lease (`--stuck-ms`) before it (it ran a stale claim);
161
+ - either run's worker came out of a pause longer than the lease just before that run started.
162
+
163
+ Jobs whose enqueue was retried by the harness (`ENQ_RETRY`) are excluded, since a second copy really exists.
164
+ If none of these applies, the job is also a **`dup_unexplained`**: something ran it twice and the harness can't point
165
+ at a fault. Treat it as a lead and read the timeline (`awk -F'\t' '$2 == <id> || $2 == -1' <tag>.events.tsv`).
166
+
167
+ Known limits: broker events count only at the moment they happen. A job whose two runs both fall inside one
168
+ disk-full window shows as unexplained even though the failed completion write explains it. Overlap uses the same
169
+ rule: a run without `END` or `CANCEL` counts as running until its worker's `KILL`/`EXIT` is logged.
170
+
171
+ `concurrent` vs `lease_overlap`: two runs of a job overlap in time (a run lasts from `START` to `END`, or to its
172
+ worker's kill/exit, or to the end of the run). If one of the workers was paused or partitioned for longer than the
173
+ lease, the overlap is `lease_overlap` (expected for lease-based queues). Otherwise it is `concurrent`, which fails the run.
174
+
175
+ Also reported: `recov_p50_ms` / `recov_max_ms` (time from a worker's death to the next start of its unfinished job),
176
+ `late_starts` (jobs whose first start came more than 30 s after the last fault, i.e. stranded and picked up late),
177
+ and when jobs are lost, the non-empty broker keys where they may be stranded.
178
+
179
+ Each run writes `<out>/<tag>.events.tsv` (raw timeline) and `<out>/<tag>.json` (config + verdict).
180
+
181
+ ## Supported queues
182
+
183
+ | Queue | Language | Broker | Adapter |
184
+ |---|---|---|---|
185
+ | Celery 5.4 | Python | Redis | [`adapters/celery`](adapters/celery) |
186
+ | RQ | Python | Redis | [`adapters/rq`](adapters/rq) |
187
+ | Dramatiq | Python | Redis | [`adapters/dramatiq`](adapters/dramatiq) |
188
+ | Huey | Python | Redis | [`adapters/huey`](adapters/huey) |
189
+ | arq | Python | Redis | [`adapters/arq`](adapters/arq) |
190
+ | Sidekiq | Ruby | Redis | [`adapters/sidekiq`](adapters/sidekiq) |
191
+ | Resque | Ruby | Redis | [`adapters/resque`](adapters/resque) |
192
+ | GoodJob | Ruby | Postgres | [`adapters/good_job`](adapters/good_job) |
193
+ | Solid Queue | Ruby | Postgres | [`adapters/solid_queue`](adapters/solid_queue) |
194
+ | BullMQ | Node | Redis | [`adapters/bullmq`](adapters/bullmq) |
195
+ | pg-boss | Node | Postgres | [`adapters/pg-boss`](adapters/pg-boss) |
196
+ | Graphile Worker | Node | Postgres | [`adapters/graphile-worker`](adapters/graphile-worker) |
197
+ | Agenda | Node | MongoDB | [`adapters/agenda`](adapters/agenda) |
198
+ | Asynq | Go | Redis | [`adapters/hibiken-asynq`](adapters/hibiken-asynq) |
199
+ | River | Go | Postgres | [`adapters/river`](adapters/river) |
200
+ | Faktory | Go client | Faktory | [`adapters/faktory`](adapters/faktory) |
201
+ | Oban | Elixir | Postgres | [`adapters/oban`](adapters/oban) |
202
+ | apalis | Rust | Redis, Postgres | [`adapters/apalis`](adapters/apalis) |
203
+ | asyncq | Rust | Redis, Postgres | [`adapters/asyncq`](adapters/asyncq) |
204
+
205
+ Setup per language is in [docs/EXAMPLES.md](docs/EXAMPLES.md#setting-up-the-bundled-adapters).
206
+ What each of these does under each fault: **[docs/GUARANTEES.md](docs/GUARANTEES.md)**.
207
+
208
+ ## Use it in CI
209
+
210
+ ```yaml
211
+ - uses: biplabku/queue-chaos@v1.0.0
212
+ with:
213
+ adapter: ./chaos/adapter
214
+ broker: redis
215
+ fault: kill
216
+ seeds: 3
217
+ ```
218
+
219
+ Full workflow: [examples/workflow.yml](examples/workflow.yml). A matrix over several faults:
220
+ [examples/workflow-matrix.yml](examples/workflow-matrix.yml).
221
+
222
+ ## Bugs found so far
223
+
224
+ | Project | Issue | What | Status |
225
+ |---|---|---|---|
226
+ | Sidekiq | [#7129](https://github.com/sidekiq/sidekiq/issues/7129) | job lost on shutdown with `-t` under ~3 s | fixed in [#7130](https://github.com/sidekiq/sidekiq/pull/7130) |
227
+ | kombu (Celery) | [#2831](https://github.com/celery/kombu/pull/2831) | message lost on Redis partition (A/B data for the fix) | merged |
228
+ | Graphile Worker | [#662](https://github.com/graphile/worker/issues/662) | worker exits after a Postgres restart | open |
229
+ | Graphile Worker | [#663](https://github.com/graphile/worker/issues/663) | jobs aborted by graceful shutdown stay locked 4 h | open |
230
+ | Dramatiq | [#925](https://github.com/Bogdanp/dramatiq/issues/925) | messages stranded in a live worker's ack set after a Redis restart | open |
231
+ | Solid Queue | [#842](https://github.com/rails/solid_queue/issues/842) | running jobs released and re-run after a finalize failure (async mode) | open |
232
+ | Agenda | [#1824](https://github.com/agenda/agenda/issues/1824) | job runs twice with default `lockLimit`, no faults needed | open |
233
+ | apalis-redis | [#127](https://github.com/apalis-dev/apalis-redis/issues/127) | worker exits on a short Redis restart | maintainer asked for a reconnect example + guide ([#128](https://github.com/apalis-dev/apalis-redis/pull/128), [website#30](https://github.com/apalis-dev/website/pull/30)), in review |
234
+ | apalis-postgres | [#141](https://github.com/apalis-dev/apalis-postgres/issues/141) (moved from apalis#832) | long task re-run by a second worker while its own worker is still running it (Postgres, defaults) | open |
235
+
236
+ Every claim has the data behind it in [FINDINGS.md](FINDINGS.md) (dated, retracted results kept visible) and a
237
+ repro under [`repros/`](repros). Found a bug with queue-chaos? Open an issue here with the upstream link and I'll add it.
238
+
239
+ ## Full study
240
+
241
+ `./run_matrix.sh 10 results` runs every queue with the same settings, then `python3 report.py` prints a
242
+ per-queue table with 95% confidence intervals. Results are stamped with a checker version and never pooled across versions.
243
+
244
+ ## How to cite
245
+
246
+ If queue-chaos helped you find a bug or you use it in a paper, please cite it (GitHub's "Cite this repository"
247
+ button, or [`CITATION.cff`](CITATION.cff)).
248
+
249
+ ## License
250
+
251
+ MIT or Apache-2.0, at your option.
@@ -0,0 +1,17 @@
1
+ chaos.py,sha256=5xsBZ7l1H1Zh5-RFLiqmPR19CfVPj0Ol-JxH2Nz2484,41377
2
+ qadvice.py,sha256=EL1PJmPrs7u-6di8_Nyap9wV5Ku7wUnMn_j2C1PkP0Y,3182
3
+ qcheck.py,sha256=Ws-dTqk4SFdtGs-5_rdqghVZqlmcszMBV7q972iMIKA,12430
4
+ queue_chaos-1.1.0.dist-info/licenses/LICENSE-APACHE,sha256=zTVPvRMCo1gVe5wrGQLlMj74TkYWWS2BTc7DvAcP25g,10279
5
+ queue_chaos-1.1.0.dist-info/licenses/LICENSE-MIT,sha256=OmNT2NzmA9Bd1bn-9C1__oi-QQq8TyZiQnt8mNpZuAc,1067
6
+ queue_chaos_presets/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ queue_chaos_presets/_common.py,sha256=IJ6ZEJw_Gi07h1qdbZ-YboKQ2hP4tfHZrRKykf4tOOI,1242
8
+ queue_chaos_presets/celery/adapter,sha256=L6yNLlfJPy607s67BpVPFe7ZoOhktUmg4FX_MqzOQ6o,451
9
+ queue_chaos_presets/celery/adapter.py,sha256=_fqXTXgzE0EN4lUVpeyGqkBNT0WQOsePLekqCQp1gJE,2774
10
+ queue_chaos_presets/rq/adapter,sha256=Mt3lBYQpdbez-oGGeFON8BZg9bgXPnClsMINvA4XDpM,280
11
+ queue_chaos_presets/rq/adapter.py,sha256=o6B4W-jy75b4pxOyhiFNEdkp72zYC_oeM88ueLHcskI,3305
12
+ queue_chaos_presets/rq/chaosjob.py,sha256=4xWXydCoK5ir9LTcTeZrsBC9im47cb-0eAH4-AtjD3s,783
13
+ queue_chaos-1.1.0.dist-info/METADATA,sha256=FWCop-UiEERqJrYM8Z3iCj_0B4wA0czBglfk-NxlQAQ,14451
14
+ queue_chaos-1.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
15
+ queue_chaos-1.1.0.dist-info/entry_points.txt,sha256=3YpXi9vTg-Dt_d2wBtdD8DAcQCOmTxOl2lul3rVWCQo,43
16
+ queue_chaos-1.1.0.dist-info/top_level.txt,sha256=bM027ZxGPmnBXg9eqoCXJS9amQvQ4BYdMPMZprgXIVI,41
17
+ queue_chaos-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ queue-chaos = chaos:main