@neralabs/rerail-pack-celery 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,210 @@
1
+ .policy "celery-practice-result-get-in-task" revision 1
2
+ .description "Chain Celery tasks instead of waiting on a result inside a task: a task blocked on .get() holds a worker slot, and when every slot waits the pool deadlocks."
3
+ .language python
4
+ .mode steer
5
+ .scope include "**/*.py"
6
+ // Rerail's own rule, not a port. A task that waits for another task's result holds its pool slot until the other
7
+ // task finishes; when every slot waits, nothing runs the tasks they wait for and the pool deadlocks (Celery tasks
8
+ // guide, "Avoid launching synchronous subtasks"). Celery guards AsyncResult.get()/wait() and ResultSet.join()/
9
+ // join_native() with assert_will_not_block(), which raises RuntimeError("Never call result.get() within a task!")
10
+ // in the worker unless the call passes disable_sync_subtasks=False or runs inside `with allow_join_result():`, so the
11
+ // code works in a shell or a web process and fails only in the worker.
12
+ // Reported at the wait: `.get()`, `.join()`, `.join_native()`, `.wait()` or `.collect()` on a result, in a task's body
13
+ // (a `@shared_task`/`@app.task` def, or the `run` of a class deriving from celery's Task) or in a function a task
14
+ // reaches through the run's call graph (named with one task that reaches it). A result is
15
+ // - `t.delay(...)`, `t.apply_async(...)`, `<x>.send_task(...)` (lib/celery's cel_send);
16
+ // - `AsyncResult(id)`, `<x>.AsyncResult(id)` (`app.`, `self.`, `celery.result.`), `GroupResult(...)`,
17
+ // `ResultSet(...)`, `GroupResult.restore(id)`, and the same for a class of the run deriving from one (pretix's
18
+ // SafeAsyncResult);
19
+ // - a group, chain or chord sent: `group(...)()`, `group(...).apply_async()`, `chord(header)(body)`, `chain(...)()`,
20
+ // `(a.s() | b.s()).apply_async()`, and `.delay()`/`.apply_async()` on a signature (`t.s(...)`, `signature(...)`);
21
+ // - a call of a function of the run that returns one of those (pretix's get_task_result);
22
+ // - a name whose latest plain assignment before the wait is one of those (`r = t.delay(x)`; `r.get()`).
23
+ // @shared_task
24
+ // def checkout(ids): return price.delay(ids[0]).get() reported
25
+ // def view(request): return price.delay(1).get() not reported: no task runs it
26
+ // Left alone: a wait passing `disable_sync_subtasks=` anything but True (DefectDojo's dojo/celery_dispatch.py does it
27
+ // deliberately); a wait inside `with allow_join_result():`, and helpers reached only through calls inside one;
28
+ // `.get()` on anything not known to be a result (dicts, caches, querysets, a name rebound to something else); status
29
+ // reads (`ready()`, `state`, `successful()`, `id`); code no task reaches; tasks and waits in test files
30
+ // (lib/celery's cel_test_doc). A function reached from both web code and a task is reported: the task path blocks.
31
+ // - an element of a list, tuple, dict or comprehension of results: `pending[i]`, and the variable of a `for` or a
32
+ // comprehension over one (`results = [t.delay(i) for i in ids]`; `[r.get() for r in results]`).
33
+ // Gaps: results passed in as parameters or stored in attributes; calls the call graph cannot resolve (python/calls'
34
+ // call_open); tasks run eagerly (`task_always_eager`), where the wait does not block, are reported all the same;
35
+ // `t.apply(...).get()` (an EagerResult: Celery raises the same RuntimeError in a worker, but nothing waits on the
36
+ // pool) is left alone. Only Celery's own sends are results (lib/celery's cel_task_ref): a thread pool's
37
+ // `apply_async(...).get()` is not.
38
+
39
+ #include "lib/celery.rerail"
40
+
41
+ .violation ResultGetInTask(at: node, m: symbol, where: symbol) "`.{m}()` waits {where} on another task: Celery raises in the worker, and the pool can deadlock. Chain the next step as a callback (chain or chord) instead of waiting."
42
+ // The tasks and the call graph between them are over definitions' symbols (decision 0677: no node crosses files):
43
+ // a task by its symbol (`pt_def`, as python/calls' `call_target` names a def), its name with it (rg_taskq). A wait is
44
+ // stated in its own file, with what its result needs of other files (rg_holds); its function is read by its symbol.
45
+ ResultGetInTask(w, m, cat("inside task `", cat(t, "`"))) :- rg_wait(w, m, nq, nk), rg_holds(nq, nk), owner(w, g),
46
+ pt_def(g, gq), rg_taskq(gq, t).
47
+ ResultGetInTask(w, m, cat("in `", cat(x, cat("()` (run by task `", cat(t, "`)"))))) :- rg_wait(w, m, nq, nk),
48
+ rg_holds(nq, nk), owner(w, g), pt_def(g, gq), !rg_is_task(gq), def_name(g, x), rg_first(gq, t).
49
+
50
+ // ---- needs -------------------------------------------------------------------------------------------------------
51
+ // rg_holds(q, k): lib/celery's cel_is, and "rg_returns": a run function (by its symbol) that returns a result. It
52
+ // spans files on purpose (pretix's get_task_result is called from other modules); symbols alone: cross_file.
53
+ .decl rg_holds(q: symbol, k: symbol) cross_file
54
+ rg_holds(q, k) :- cel_is(q, k).
55
+ rg_holds(gq, "rg_returns") :- rg_returns_if(gq, nq, nk), rg_holds(nq, nk).
56
+ .decl rg_returns_if(g: symbol, nq: symbol, nk: symbol)
57
+ rg_returns_if(gq, nq, nk) :- kind(r, "return_statement"), child(r, v, 0), rg_result(v, nq, nk), nearest(r, g, fdef),
58
+ pt_def(g, gq).
59
+
60
+ // ---- tasks and what they run --------------------------------------------------------------------------------------
61
+ // rg_task(f, nq, nk): a task outside test files: a cel_task def, or the `run` method of a class deriving from celery's
62
+ // Task (lib/celery's "task_cls", through the run's classes).
63
+ .decl rg_task(f: node, nq: symbol, nk: symbol)
64
+ rg_task(f, nq, nk) :- cel_task(f, nq, nk), docof(f, d), !cel_test_doc(d).
65
+ rg_task(f, b, "task_cls") :- kind(c, "class_definition"), cel_class_base(c, b), field(c, "body", cb), child(cb, f, _),
66
+ kind(f, "function_definition"), def_name(f, "run"), docof(f, d), !cel_test_doc(d).
67
+ // rg_taskq(f, t): task f, by symbol, named t. A fact of the run: what each file states of its tasks (rg_task_sym),
68
+ // with their needs met.
69
+ .decl rg_task_sym(f: symbol, t: symbol, nq: symbol, nk: symbol)
70
+ rg_task_sym(fq, t, nq, nk) :- rg_task(f, nq, nk), pt_def(f, fq), def_name(f, t).
71
+ .decl rg_taskq(f: symbol, t: symbol)
72
+ rg_taskq(fq, t) :- rg_task_sym(fq, t, nq, nk), rg_holds(nq, nk).
73
+ .decl rg_is_task(f: symbol)
74
+ rg_is_task(fq) :- rg_taskq(fq, _).
75
+ // rg_reach_q(f, g): task f runs g: g is f, or a call outside `with allow_join_result():` leads from f to g (each
76
+ // file's calls by symbol: rg_calls_q). The call graph spans files: cross_file, symbols alone.
77
+ .decl rg_calls_q(f: symbol, g: symbol)
78
+ rg_calls_q(fq, gq) :- owner(c, f), call_target(c, gq), !rg_allowed(c), pt_def(f, fq).
79
+ .decl rg_reach_q(f: symbol, g: symbol) cross_file
80
+ rg_reach_q(fq, fq) :- rg_is_task(fq).
81
+ rg_reach_q(fq, hq) :- rg_reach_q(fq, gq), rg_calls_q(gq, hq).
82
+ // rg_first(g, t): of the tasks that run g, the least symbol's (one task named for the message), named t.
83
+ .decl rg_first(g: symbol, t: symbol)
84
+ rg_first(gq, t) :- rg_reach_q(fq, gq), !rg_later(fq, gq), rg_taskq(fq, t).
85
+ .decl rg_later(f: symbol, g: symbol)
86
+ rg_later(fq, gq) :- rg_reach_q(fq, gq), rg_reach_q(eq, gq), eq < fq.
87
+
88
+ // ---- opt-outs ---------------------------------------------------------------------------------------------------
89
+ // rg_allowed(n): n runs in the body of `with allow_join_result():` (in the same def).
90
+ .decl rg_allowed(n: node)
91
+ rg_allowed(n) :- kind(ws, "with_statement"), child(ws, wc, _), kind(wc, "with_clause"), child(wc, wi, _),
92
+ kind(wi, "with_item"), field(wi, "value", v), unparen(v, k), kind(k, "call"), field(k, "function", fn),
93
+ leaf_name(fn, "allow_join_result"), field(ws, "body", b), within_stop(n, b, cel_region_stop).
94
+ // rg_optout(w): the wait passes disable_sync_subtasks= anything but the literal True.
95
+ .decl rg_optout(w: node)
96
+ rg_optout(w) :- call_arg(w, -1, "disable_sync_subtasks", v), !kind(v, "true").
97
+
98
+ // ---- results ----------------------------------------------------------------------------------------------------
99
+ // rg_canvas(e, k, nq, nk): e is a signature ("sig": `t.s(...)`, `t.si(...)`, `t.signature(...)`, `signature(...)`) or
100
+ // a group, chain or chord ("multi": `group(...)`, `chain(...)`, `chord(...)`, `a | b`), or a name last assigned one.
101
+ .decl rg_canvas_fn(q: symbol, k: symbol)
102
+ rg_canvas_fn("celery.signature", "sig"). rg_canvas_fn("celery.Signature", "sig").
103
+ rg_canvas_fn("celery.canvas.signature", "sig"). rg_canvas_fn("celery.canvas.Signature", "sig").
104
+ rg_canvas_fn("celery.group", "multi"). rg_canvas_fn("celery.canvas.group", "multi").
105
+ rg_canvas_fn("celery.chain", "multi"). rg_canvas_fn("celery.canvas.chain", "multi").
106
+ rg_canvas_fn("celery.canvas._chain", "multi"). rg_canvas_fn("celery.chord", "multi").
107
+ rg_canvas_fn("celery.canvas.chord", "multi").
108
+ .decl rg_canvas(e: node, k: symbol, nq: symbol, nk: symbol)
109
+ rg_canvas(e, k, "", "") :- unparen(e, u), kind(u, "call"), field(u, "function", fn), sym_of(fn, q), rg_canvas_fn(q, k).
110
+ rg_canvas(e, "sig", nq, nk) :- unparen(e, u), kind(u, "call"), field(u, "function", fn), attr_of(fn, o, m),
111
+ (m = "s" ; m = "si" ; m = "signature"), unparen(o, t), cel_task_ref(t, nq, nk).
112
+ // `sig.set(queue=...)`, `sig.clone()` return a signature of the same kind.
113
+ rg_canvas(e, k, nq, nk) :- unparen(e, u), kind(u, "call"), field(u, "function", fn), attr_of(fn, o, m),
114
+ (m = "set" ; m = "clone"), rg_canvas(o, k, nq, nk).
115
+ rg_canvas(e, "multi", nq, nk) :- unparen(e, u), kind(u, "binary_operator"), op(u, "|"), child(u, x, _),
116
+ rg_canvas(x, _, nq, nk).
117
+ rg_canvas(e, k, nq, nk) :- unparen(e, u), kind(u, "identifier"), text(u, x), latest_assign(u, x, a), rasg(_, x, v, a),
118
+ rg_canvas(v, k, nq, nk).
119
+ // rg_result_cls(q): result classes, whose constructor and `restore` give a result; a class of the run deriving from
120
+ // one (pretix's SafeAsyncResult) too (lib/celery's cel_derives: py_names' ancestors).
121
+ .decl rg_result_cls(q: symbol)
122
+ rg_result_cls("celery.result.AsyncResult"). rg_result_cls("celery.AsyncResult").
123
+ rg_result_cls("celery.result.GroupResult"). rg_result_cls("celery.GroupResult").
124
+ rg_result_cls("celery.result.ResultSet"). rg_result_cls("celery.ResultSet").
125
+ .decl rg_result_ref(c: node)
126
+ rg_result_ref(c) :- cel_derives(c, b), rg_result_cls(b).
127
+ // rg_result(e, nq, nk): e holds an AsyncResult, GroupResult or ResultSet.
128
+ .decl rg_result(e: node, nq: symbol, nk: symbol)
129
+ rg_result(e, nq, nk) :- unparen(e, u), cel_send(u, _, nq, nk).
130
+ rg_result(e, "", "") :- unparen(e, u), kind(u, "call"), field(u, "function", fn), rg_result_ref(fn).
131
+ rg_result(e, "", "") :- unparen(e, u), kind(u, "call"), field(u, "function", fn), attr_of(fn, _, m),
132
+ (m = "AsyncResult" ; m = "GroupResult").
133
+ rg_result(e, "", "") :- unparen(e, u), kind(u, "call"), field(u, "function", fn), attr_of(fn, o, "restore"),
134
+ unparen(o, c), (rg_result_ref(c) ; attr_of(c, _, "GroupResult")).
135
+ rg_result(e, nq, nk) :- unparen(e, u), kind(u, "call"), field(u, "function", fn), attr_of(fn, o, m),
136
+ (m = "delay" ; m = "apply_async"), rg_canvas(o, _, nq, nk).
137
+ rg_result(e, nq, nk) :- unparen(e, u), kind(u, "call"), field(u, "function", fn), rg_canvas(fn, "multi", nq, nk).
138
+ rg_result(e, nq, nk) :- unparen(e, u), kind(u, "identifier"), text(u, x), latest_assign(u, x, a), rasg(_, x, v, a),
139
+ rg_result(v, nq, nk).
140
+ // A call of a function of the run that returns a result (pretix's get_task_result): its symbol is "rg_returns".
141
+ rg_result(e, gq, "rg_returns") :- unparen(e, u), kind(u, "call"), call_target(u, gq).
142
+ // A result taken from a collection of them: `pending[i]` with pending a dict or list of results, and the loop
143
+ // variable of a `for` statement or comprehension clause over one (`[r.get() for r in results]`).
144
+ rg_result(e, nq, nk) :- unparen(e, u), kind(u, "subscript"), field(u, "value", c), rg_results(c, nq, nk).
145
+ rg_result(e, nq, nk) :- unparen(e, u), kind(u, "identifier"), text(u, x), kind(fc, "for_in_clause"),
146
+ field(fc, "left", l), kind(l, "identifier"), text(l, x), field(fc, "right", it), rg_results(it, nq, nk),
147
+ child(comp, fc, _), within(u, comp), u != l.
148
+ rg_result(e, nq, nk) :- unparen(e, u), kind(u, "identifier"), text(u, x), kind(fs, "for_statement"),
149
+ field(fs, "left", l), kind(l, "identifier"), text(l, x), field(fs, "right", it), rg_results(it, nq, nk),
150
+ field(fs, "body", b), within(u, b).
151
+ // rg_results(e, nq, nk): e holds a list, set, dict or generator of results: a literal or comprehension of them, or a
152
+ // name whose latest plain assignment is one.
153
+ .decl rg_results(e: node, nq: symbol, nk: symbol)
154
+ rg_results(e, nq, nk) :- unparen(e, u), (kind(u, "list_comprehension") ; kind(u, "set_comprehension") ;
155
+ kind(u, "generator_expression")), field(u, "body", b), rg_result(b, nq, nk).
156
+ rg_results(e, nq, nk) :- unparen(e, u), kind(u, "dictionary_comprehension"), field(u, "body", p), field(p, "value", v),
157
+ rg_result(v, nq, nk).
158
+ rg_results(e, nq, nk) :- unparen(e, u), (kind(u, "list") ; kind(u, "tuple")), child(u, x, _), rg_result(x, nq, nk).
159
+ rg_results(e, nq, nk) :- unparen(e, u), kind(u, "identifier"), text(u, x), latest_assign(u, x, a), rasg(_, x, v, a),
160
+ rg_results(v, nq, nk).
161
+
162
+ // ---- waits ------------------------------------------------------------------------------------------------------
163
+ .decl rg_wait_method(m: symbol)
164
+ rg_wait_method("get"). rg_wait_method("join"). rg_wait_method("join_native"). rg_wait_method("wait").
165
+ rg_wait_method("collect").
166
+ // rg_wait(w, m, nq, nk): call w is `r.m(...)` on a result r, not opted out, not under allow_join_result, outside test
167
+ // files.
168
+ .decl rg_wait(w: node, m: symbol, nq: symbol, nk: symbol)
169
+ rg_wait(w, m, nq, nk) :- kind(w, "call"), field(w, "function", fn), attr_of(fn, o, m), rg_wait_method(m),
170
+ rg_result(o, nq, nk), !rg_optout(w), !rg_allowed(w), docof(w, d), !cel_test_doc(d).
171
+
172
+ // The cases, `upstream/celery-practice/authored/celery-practice-result-get-in-task/`, read as one repository: each line
173
+ // ending in `# caught` is reported, and no other line.
174
+ .test cases exactly
175
+ .fixture "proj/__init__.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/__init__.py"
176
+ .fixture "proj/celery.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/celery.py"
177
+ .fixture "proj/fanout.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/fanout.py"
178
+ .fixture "proj/helpers.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/helpers.py"
179
+ .fixture "proj/results.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/results.py"
180
+ .fixture "proj/pools.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/pools.py"
181
+ .fixture "proj/tasks.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/tasks.py"
182
+ .fixture "proj/tests/__init__.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/tests/__init__.py"
183
+ .fixture "proj/tests/test_tasks.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/tests/test_tasks.py"
184
+ .fixture "proj/web/__init__.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/web/__init__.py"
185
+ .fixture "proj/web/views.py" from "../upstream/celery-practice/authored/celery-practice-result-get-in-task/proj/web/views.py"
186
+ .expect _ at "proj/fanout.py":15
187
+ .expect _ at "proj/fanout.py":21
188
+ .expect _ at "proj/fanout.py":29
189
+ .expect _ at "proj/fanout.py":37
190
+ .expect _ at "proj/helpers.py":11
191
+ .expect _ at "proj/helpers.py":15
192
+ .expect _ at "proj/results.py":23
193
+ .expect _ at "proj/results.py":25
194
+ .expect _ at "proj/tasks.py":21
195
+ .expect _ at "proj/tasks.py":23
196
+ .expect _ at "proj/tasks.py":25
197
+ .expect _ at "proj/tasks.py":27
198
+ .expect _ at "proj/tasks.py":28
199
+ .expect _ at "proj/tasks.py":29
200
+ .expect _ at "proj/tasks.py":30
201
+ .expect _ at "proj/tasks.py":31
202
+ .expect _ at "proj/tasks.py":32
203
+ .expect _ at "proj/tasks.py":34
204
+ .expect _ at "proj/tasks.py":35
205
+ .expect _ at "proj/tasks.py":36
206
+ .expect _ at "proj/tasks.py":37
207
+ .expect _ at "proj/tasks.py":39
208
+ .expect _ at "proj/tasks.py":40
209
+ .expect _ at "proj/tasks.py":41
210
+ .end
@@ -0,0 +1,279 @@
1
+ .policy "celery-practice-task-arg-not-serializable" revision 1
2
+ .description "Pass a Celery task plain data (ids, strings, lists, dicts), never a SQLAlchemy model or session, a set, an open file, a lambda, a generator or a function."
3
+ .language python
4
+ .mode steer
5
+ .scope include "**/*.py"
6
+ // Rerail's own rule, not a port. Celery serializes a task's arguments into the message, with JSON by default (kombu's
7
+ // encoder adds datetime, date, time, Decimal, UUID and bytes, nothing else). An argument it cannot encode makes the
8
+ // send raise EncodeError; with pickle, a SQLAlchemy model arrives as a detached snapshot that is stale when the worker
9
+ // runs, and saving it there overwrites newer changes.
10
+ //
11
+ // It matches an argument a task receives (lib/celery's cel_task_arg: `delay`, `s`, `si`, `apply_async` and
12
+ // `send_task` args and kwargs, `**{...}` and `*[...]` spreads, `kwargs=dict(...)`) of a call on a Celery task
13
+ // (cel_task_call: the def resolves through imports) or a send on a task reference (cel_send: only what resolves to a
14
+ // Celery task, so RQ's `@job(...).delay` or a thread pool's `apply_async` is not one), when the argument is
15
+ // - a SQLAlchemy model instance (lib/celery's sa_instance: `M(...)`, `session.get(M, pk)`,
16
+ // `session.scalar(select(M)...)`, `M.query...first()`, a name bound to one, a parameter annotated `M`, a value the
17
+ // type program proves is a model), `self` in a method of a model, Flask-Login's `current_user` (a proxy of the
18
+ // user model), or a list, tuple or dict literal holding one; outside files that import django (the django pack's
19
+ // django-practice-task-arg-model-instance owns those);
20
+ // - a SQLAlchemy session proven by what binds it (lib/celery's sa_session_proven: a session class's constructor, a
21
+ // sessionmaker or scoped_session, Flask-SQLAlchemy's `db.session`, a run function returning or yielding one, an
22
+ // annotation with a session class, also through `Annotated` aliases), or, by name alone, an unannotated parameter
23
+ // named like a session that its function never rebinds, in a run that imports SQLAlchemy (sa_session_guess);
24
+ // - a set or frozenset: a literal, a comprehension, a `set(...)`/`frozenset(...)` call, a `|`, `&`, `-` or `^` with
25
+ // one of those, or a name whose last assignment before the send is one of those;
26
+ // - an open file: `open(...)`, a name whose last assignment is one, or the target of `with open(...) as f`;
27
+ // - a lambda or a generator expression;
28
+ // - a function of the run passed by name.
29
+ // A task declared `serializer="pickle"`, a send with `serializer="pickle"`, or an app whose task_serializer names
30
+ // pickle (any spelling, `signed-pickle` too) can carry sets and module-level functions, so those shapes are left
31
+ // alone there; models, sessions, files, lambdas and generators are still reported (pickle raises on the last four).
32
+ // order = session.get(Order, pk); ship.delay(order) reported
33
+ // tag.delay({"a", "b"}) reported
34
+ // ship.delay(order.id); tag.delay(sorted(tags)) not reported
35
+ // tag.delay(datetime.now(), Decimal("1"), uuid4(), b"x") not reported (kombu encodes them)
36
+ // A run whose Task subclass (resolved through bases, or `<app>.Task` / `self.Task` in a Celery subclass) overrides
37
+ // apply_async and rewrites its args or kwargs there (indico's _CelerySAWrapper turns each model into its identity key
38
+ // and re-fetches it in the worker) is left alone for the model shape.
39
+ // Left alone too: a local named `session` bound to anything else (a string, a dict, a request field, a requests or
40
+ // aiohttp session), and a parameter annotated with a type that is not a SQLAlchemy session. Test files are skipped.
41
+ // Gaps: values whose kind only a type checker knows (a helper's return the type program cannot follow); instances
42
+ // inside comprehensions or containers built elsewhere; related objects (`order.customer`); dataclass and Pydantic
43
+ // instances (left out: kombu honours a `__json__` method, and some projects register them); a model whose class
44
+ // defines `__json__` (kombu encodes it, but the snapshot is still stale); a project that registers `set` with
45
+ // kombu's register_type; a serializer chosen in a router or a Task subclass.
46
+
47
+ #include "lib/celery.rerail"
48
+
49
+ // Each call and argument is stated in its own file, with what its task and its value need of other files (lib/celery's
50
+ // needs, cel_is): the task def a call names (q, "task"), the model class an argument is an instance of. What the run
51
+ // does as a whole (a pickling app, a Task subclass that rewrites arguments, a task declared pickled) are facts over
52
+ // symbols (tas_app_pickled, tas_wrapped, tas_pickled_q: cross_file).
53
+ .violation TaskArgModel(at: node, task: symbol, arg: symbol) "`{arg}` is a SQLAlchemy model passed to task `{task}`: JSON cannot encode it, and pickle sends a copy that is stale when the task runs. Pass its primary key and load the row in the task."
54
+ TaskArgModel(a, t, x) :- tas_call(c, t, _, nq, nk), cel_is(nq, nk), cel_task_arg(c, a), tas_model(a, mq, mk),
55
+ cel_is(mq, mk), text(a, x), docof(c, d), !cel_django_doc(d), !tas_wrapped().
56
+
57
+ // tas_model(a, nq, nk): lib/celery's sa_instance, `self` in a method of a model (`notify.delay(self)` in
58
+ // `Order.place`), Flask-Login's current_user, or a list, tuple or dict literal holding one.
59
+ .decl tas_model(a: node, nq: symbol, nk: symbol)
60
+ tas_model(a, nq, nk) :- sa_instance(a, nq, nk).
61
+ tas_model(a, nq, nk) :- unparen(a, e), kind(e, "identifier"), text(e, "self"), look(e, "self", f),
62
+ param(f, "self", 0), nearest(f, k, scope), sa_model(k, nq, nk).
63
+ tas_model(a, "", "") :- unparen(a, e), (sym_of(e, "flask_login.current_user") ;
64
+ sym_of(e, "flask_login.utils.current_user")).
65
+ tas_model(a, nq, nk) :- unparen(a, e), (kind(e, "list") ; kind(e, "tuple")), child(e, x, _), tas_model(x, nq, nk).
66
+ tas_model(a, nq, nk) :- unparen(a, e), cel_dict_value(e, x), tas_model(x, nq, nk).
67
+
68
+ // tas_wrapped(): a Task subclass of the run defines `apply_async` and assigns `args` or `kwargs` there: the run
69
+ // converts arguments before they reach the serializer. A fact of the whole run (cross_file, no column), from each
70
+ // file's wrappers (tas_arg_wrapper) with their needs met.
71
+ .decl tas_wrapped() cross_file
72
+ tas_wrapped() :- tas_wrapper_need(nq, nk), cel_is(nq, nk).
73
+ .decl tas_wrapper_need(nq: symbol, nk: symbol)
74
+ tas_wrapper_need(nq, nk) :- tas_arg_wrapper(_, nq, nk).
75
+ .decl tas_arg_wrapper(g: node, nq: symbol, nk: symbol)
76
+ tas_arg_wrapper(g, nq, nk) :- kind(g, "function_definition"), def_name(g, "apply_async"), nearest(g, k, scope),
77
+ kind(k, "class_definition"), tas_task_class(k, nq, nk), (asg(g, "args", _, _) ; asg(g, "kwargs", _, _)).
78
+ // tas_task_class(k, nq, nk): k derives from celery's Task (lib/celery's "task_cls", through the run's classes), or
79
+ // from `<app>.Task`, the app's task base (`app.Task`, or `self.Task` in a method of a Celery subclass: py_names'
80
+ // ancestors, python/names' class_anc).
81
+ .decl tas_task_class(k: node, nq: symbol, nk: symbol)
82
+ tas_task_class(k, b, "task_cls") :- cel_class_base(k, b).
83
+ tas_task_class(k, nq, nk) :- field(k, "superclasses", al), child(al, e, _), attr_of(e, o, "Task"), unparen(o, u),
84
+ cel_app_ref(u, nq, nk).
85
+ tas_task_class(k, "", "") :- field(k, "superclasses", al), child(al, e, _), attr_of(e, o, "Task"), unparen(o, u),
86
+ text(u, "self"), nearest(k, f, fdef), nearest(f, c, scope), kind(c, "class_definition"), class_anc(c, b),
87
+ cel_app_class(b).
88
+
89
+ .violation TaskArgSession(at: node, task: symbol, arg: symbol) "`{arg}` is a SQLAlchemy session passed to task `{task}`; no serializer can carry it to a worker. Pass the ids the task needs and open a session inside the task."
90
+ TaskArgSession(a, t, x) :- tas_call(c, t, _, nq, nk), cel_is(nq, nk), cel_task_arg(c, a), tas_session(a, sq, sk),
91
+ cel_is(sq, sk), text(a, x).
92
+
93
+ .violation TaskArgSet(at: node, task: symbol, arg: symbol) "`{arg}` is a set passed to task `{task}`; Celery's default JSON serializer cannot encode sets. Pass a list (`sorted(...)` or `list(...)`) and rebuild the set in the task."
94
+ TaskArgSet(a, t, x) :- tas_call(c, t, q, nq, nk), cel_is(nq, nk), cel_task_arg(c, a), tas_set(a), !tas_pickled_here(c),
95
+ !tas_pickled_q(q), !tas_app_pickled(), text(a, x).
96
+
97
+ .violation TaskArgFile(at: node, task: symbol, arg: symbol) "`{arg}` is an open file passed to task `{task}`; no serializer can encode it, and the worker may run elsewhere. Pass the file's path, or its contents if they are small."
98
+ TaskArgFile(a, t, x) :- tas_call(c, t, _, nq, nk), cel_is(nq, nk), cel_task_arg(c, a), tas_file(a), text(a, x).
99
+
100
+ .violation TaskArgCallable(at: node, task: symbol, arg: symbol, what: symbol) "`{arg}` is {what} passed to task `{task}`; Celery's default JSON serializer cannot encode it. Pass the values themselves, or a name the task maps to the function."
101
+ TaskArgCallable(a, t, x, w) :- tas_call(c, t, _, nq, nk), cel_is(nq, nk), cel_task_arg(c, a), tas_callable(c, a, w),
102
+ text(a, x).
103
+ // A function of the run named bare: a module-level function pickles by reference, so a pickled message leaves it.
104
+ TaskArgCallable(a, t, x, "a function") :- tas_call(c, t, q, nq, nk), cel_is(nq, nk), cel_task_arg(c, a),
105
+ tas_function(a), !tas_pickled_here(c), !tas_pickled_q(q), !tas_app_pickled(), text(a, x).
106
+ TaskArgCallable(g, t, x, "a generator expression") :- tas_call(c, t, _, nq, nk), cel_is(nq, nk),
107
+ tas_bare_generator(c, g), text(g, x).
108
+
109
+ // tas_call(c, t, q, nq, nk): c is a task call or send outside test files; t names the task for the message; q is the
110
+ // task def's symbol when c names one (cel_task_call), else "".
111
+ .decl tas_call(c: node, t: symbol, q: symbol, nq: symbol, nk: symbol)
112
+ tas_call(c, t, q, q, "task") :- cel_task_call(c, q, _), split_dot(q, _, t), tas_live(c).
113
+ tas_call(c, t, "", nq, nk) :- cel_send(c, m, nq, nk), m != "send_task", !tas_def_call(c), field(c, "function", fn),
114
+ attr_of(fn, o, _), text(o, t), tas_live(c).
115
+ tas_call(c, t, "", "", "") :- cel_send(c, "send_task", _, _), cel_name_ref(e, t, "send_task", _, _),
116
+ child(al, e, _), field(c, "arguments", al), tas_live(c).
117
+ tas_call(c, "?", "", "", "") :- cel_send(c, "send_task", _, _), !tas_named_send(c), tas_live(c).
118
+ // tas_def_call(c): c's receiver resolves to a def of the run (cel_task_call), named by the first rule when it is a
119
+ // task, and no task otherwise.
120
+ .decl tas_def_call(c: node)
121
+ tas_def_call(c) :- cel_task_call(c, _, _).
122
+ .decl tas_named_send(c: node)
123
+ tas_named_send(c) :- cel_send(c, "send_task", _, _), field(c, "arguments", al), child(al, e, _),
124
+ cel_name_ref(e, _, "send_task", _, _).
125
+ .decl tas_live(c: node)
126
+ tas_live(c) :- kind(c, "call"), docof(c, d), !cel_test_doc(d).
127
+
128
+ // `tag.delay(r for r in rows)`: the generator is the call's whole argument list, which call_arg does not list.
129
+ .decl tas_bare_generator(c: node, g: node)
130
+ tas_bare_generator(c, g) :- kind(c, "call"), field(c, "function", fn), attr_of(fn, _, m), (m = "delay" ; m = "s" ;
131
+ m = "si"), field(c, "arguments", g), kind(g, "generator_expression").
132
+
133
+ // The message of call c is pickled when its task says `serializer="pickle"` (tas_pickled_q, the task's symbol), the
134
+ // call does (tas_pickled_here), or an app of the run sets task_serializer to a pickle serializer (tas_app_pickled).
135
+ .decl tas_pickled_here(c: node)
136
+ tas_pickled_here(c) :- kind(c, "call"), call_arg(c, -1, "serializer", v), tas_pickle_str(v).
137
+ .decl tas_pickled_q(q: symbol) cross_file
138
+ tas_pickled_q(q) :- tas_pickled_def(q, nq, nk), cel_is(nq, nk).
139
+ .decl tas_pickled_def(q: symbol, nq: symbol, nk: symbol)
140
+ tas_pickled_def(q, nq, nk) :- cel_task_option(f, "serializer", v, nq, nk), tas_pickle_str(v), qualname(f, q).
141
+ .decl tas_app_pickled() cross_file
142
+ tas_app_pickled() :- tas_pickle_setting(_).
143
+ .decl tas_pickle_setting(d: number)
144
+ tas_pickle_setting(d) :- cel_setting("task_serializer", v, _), tas_pickle_str(v), docof(v, d).
145
+ .decl tas_pickle_str(v: node)
146
+ tas_pickle_str(v) :- str(v, s), contains("pickle", s).
147
+
148
+ // tas_session(a, nq, nk): a session proven by what binds it (lib/celery's sa_session_proven), or the name fallback
149
+ // (sa_session_guess, in a run that imports SQLAlchemy) only for a name its function never assigns (an unannotated
150
+ // parameter): an attribute or a local the engine cannot follow is not reported.
151
+ .decl tas_session(a: node, nq: symbol, nk: symbol)
152
+ tas_session(a, nq, nk) :- unparen(a, e), sa_session_proven(e, nq, nk).
153
+ tas_session(a, "", "sa_run") :- unparen(a, e), kind(e, "identifier"), sa_session_guess(e), text(e, x), look(e, x, f),
154
+ param(f, x, _), !asg(f, x, _, _), !sa_with_alias(e, _).
155
+
156
+ // tas_set(a): a set or frozenset value.
157
+ .decl tas_set(a: node)
158
+ tas_set(a) :- unparen(a, e), tas_set_value(e).
159
+ tas_set(a) :- unparen(a, e), kind(e, "identifier"), latest_assign(e, x, s), text(e, x), field(s, "right", v),
160
+ unparen(v, w), tas_set_value(w).
161
+ .decl tas_set_value(v: node)
162
+ tas_set_value(v) :- kind(v, "set").
163
+ tas_set_value(v) :- kind(v, "set_comprehension").
164
+ tas_set_value(v) :- kind(v, "call"), field(v, "function", f), (sym_of(f, "builtins.set") ; sym_of(f, "builtins.frozenset")).
165
+ // A set operator with a set operand gives a set (`tags | {"x"}`; `|` on two dicts gives a dict, so one side must be
166
+ // a set).
167
+ tas_set_value(v) :- kind(v, "binary_operator"), (op(v, "|") ; op(v, "&") ; op(v, "-") ; op(v, "^")), child(v, x, _),
168
+ tas_set(x).
169
+
170
+ // tas_file(a): an open file object.
171
+ .decl tas_file(a: node)
172
+ tas_file(a) :- unparen(a, e), tas_open(e).
173
+ tas_file(a) :- unparen(a, e), kind(e, "identifier"), latest_assign(e, x, s), text(e, x), field(s, "right", v),
174
+ unparen(v, w), tas_open(w).
175
+ tas_file(a) :- unparen(a, e), kind(e, "identifier"), text(e, x), kind(wi, "with_item"), field(wi, "value", ap),
176
+ kind(ap, "as_pattern"), child(ap, o, 0), unparen(o, w), tas_open(w), field(ap, "alias", al), text(al, x),
177
+ nearest(wi, ws, "with_statement"), field(ws, "body", b), within(e, b).
178
+ .decl tas_open(v: node)
179
+ tas_open(v) :- kind(v, "call"), field(v, "function", f), (sym_of(f, "builtins.open") ; sym_of(f, "io.open")).
180
+
181
+ // tas_callable(c, a, what): a lambda or a generator expression. tas_function(a): a function of the run named bare (a
182
+ // def of the run, py_names' defined and no class, or a def its own scope binds).
183
+ .decl tas_callable(c: node, a: node, what: symbol)
184
+ tas_callable(c, a, "a lambda") :- cel_task_arg(c, a), unparen(a, e), kind(e, "lambda").
185
+ tas_callable(c, a, "a generator expression") :- cel_task_arg(c, a), unparen(a, e), kind(e, "generator_expression").
186
+ .decl tas_function(a: node)
187
+ tas_function(a) :- unparen(a, e), kind(e, "identifier"), sym_of(e, q), docof(e, d), doc(d, p, _),
188
+ py_names__reads_at(p, m), py_names__defined(m, q), !py_names__class(m, q).
189
+ tas_function(a) :- unparen(a, e), kind(e, "identifier"), text(e, x), look(e, x, s), !kind(s, "module"),
190
+ defn(s, x, g), kind(g, "function_definition").
191
+
192
+ // The cases, `upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/`, read as one repository:
193
+ // each line ending in `# caught` is reported, and no other line. `pickled/` is an app that sets task_serializer to
194
+ // pickle, so it is its own repository.
195
+ .test cases exactly
196
+ .fixture "proj/__init__.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/__init__.py"
197
+ .fixture "proj/celery.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/celery.py"
198
+ .fixture "proj/models.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/models.py"
199
+ .fixture "proj/tasks.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/tasks.py"
200
+ .fixture "proj/services.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/services.py"
201
+ .fixture "proj/fine.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/fine.py"
202
+ .fixture "proj/db.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/db.py"
203
+ .fixture "proj/rq_jobs.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/rq_jobs.py"
204
+ .fixture "proj/sessions.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/sessions.py"
205
+ .fixture "proj/decorators.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/decorators.py"
206
+ .fixture "proj/reexport.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/reexport.py"
207
+ .fixture "proj/uses.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/uses.py"
208
+ .fixture "proj/ops.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/ops.py"
209
+ .fixture "proj/tests/test_services.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/proj/tests/test_services.py"
210
+ .fixture "dj/__init__.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/dj/__init__.py"
211
+ .fixture "dj/views.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/dj/views.py"
212
+ .expect _ at "dj/views.py":10
213
+ .expect _ at "proj/sessions.py":19
214
+ .expect _ at "proj/sessions.py":21
215
+ .expect _ at "proj/sessions.py":22
216
+ .expect _ at "proj/sessions.py":23
217
+ .expect _ at "proj/sessions.py":24
218
+ .expect _ at "proj/sessions.py":26
219
+ .expect _ at "proj/sessions.py":28
220
+ .expect _ at "proj/sessions.py":32
221
+ .expect _ at "proj/sessions.py":33
222
+ .expect _ at "proj/sessions.py":38
223
+ .expect _ at "proj/sessions.py":44
224
+ .expect _ at "proj/sessions.py":45
225
+ .expect _ at "proj/sessions.py":46
226
+ .expect _ at "proj/sessions.py":47
227
+ .expect _ at "proj/sessions.py":48
228
+ .expect _ at "proj/sessions.py":49
229
+ .expect _ at "proj/sessions.py":50
230
+ .expect _ at "proj/sessions.py":95
231
+ .expect _ at "proj/uses.py":8
232
+ .expect _ at "proj/uses.py":9
233
+ .expect _ at "proj/uses.py":10
234
+ .expect _ at "proj/uses.py":11
235
+ .expect _ at "proj/uses.py":12
236
+ .expect _ at "proj/uses.py":13
237
+ .expect _ at "proj/models.py":15
238
+ .expect _ at "proj/services.py":15
239
+ .expect _ at "proj/services.py":16
240
+ .expect _ at "proj/services.py":17
241
+ .expect _ at "proj/services.py":18
242
+ .expect _ at "proj/services.py":19
243
+ .expect _ at "proj/services.py":20
244
+ .expect _ at "proj/services.py":24
245
+ .expect _ at "proj/services.py":29
246
+ .expect _ at "proj/services.py":33
247
+ .expect _ at "proj/services.py":34
248
+ .expect _ at "proj/services.py":35
249
+ .expect _ at "proj/services.py":36
250
+ .expect _ at "proj/services.py":38
251
+ .expect _ at "proj/services.py":39
252
+ .expect _ at "proj/services.py":43
253
+ .expect _ at "proj/services.py":44
254
+ .expect _ at "proj/services.py":45
255
+ .expect _ at "proj/services.py":47
256
+ .expect _ at "proj/services.py":49
257
+ .expect _ at "proj/services.py":50
258
+ .expect _ at "proj/services.py":51
259
+ .end
260
+
261
+ .test pickled_app exactly
262
+ .fixture "pickled/__init__.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/pickled/__init__.py"
263
+ .fixture "pickled/celery.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/pickled/celery.py"
264
+ .fixture "pickled/models.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/pickled/models.py"
265
+ .fixture "pickled/jobs.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/pickled/jobs.py"
266
+ .expect _ at "pickled/jobs.py":16
267
+ .expect _ at "pickled/jobs.py":17
268
+ .expect _ at "pickled/jobs.py":21
269
+ .expect _ at "pickled/jobs.py":22
270
+ .expect _ at "pickled/jobs.py":23
271
+ .end
272
+
273
+ .test wrapped_app exactly
274
+ .fixture "wrapped/__init__.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/wrapped/__init__.py"
275
+ .fixture "wrapped/celery.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/wrapped/celery.py"
276
+ .fixture "wrapped/models.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/wrapped/models.py"
277
+ .fixture "wrapped/jobs.py" from "../upstream/celery-practice/authored/celery-practice-task-arg-not-serializable/wrapped/jobs.py"
278
+ .expect _ at "wrapped/jobs.py":13
279
+ .end