1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// SPDX-FileCopyrightText: 2026 Alexander Merose <al@merose.com> & ddx Authors
//
// SPDX-License-Identifier: Apache-2.0
//! Path B across awkward plan shapes and binding edges.
//!
//! Each test here started as a claim the crate made about itself that a live
//! engine did not honour. They assert on *executed numbers* rather than on
//! rewritten SQL, because every bug this rewrite has had was invisible to
//! reading and only surfaced when a query actually ran.
//!
//! The recurring theme, and the thing to keep in mind when editing the analyzer:
//! an `AnalyzerRule` runs *after* the planner has bound columns, coerced types,
//! and cached schemas, so a rewrite must hand back an expression consistent with
//! all three — and it must reach every corner of the plan the planner filled in,
//! including the ones that live inside expressions rather than under `inputs()`.
use Arc;
use ;
use DataType;
use Result;
use ;
use ;
/// A context with ddx installed and `t(x, y)` = {(1,4), (2,5), (3,6)}.
async
/// Run `sql`, returning the first column as `f64`s.
async
// ---------------------------------------------------------------------------
// Subqueries embedded in expressions, including the quantified forms.
// ---------------------------------------------------------------------------
/// A marker inside a quantified-comparison subquery — `> ALL (…)`, `= ANY (…)`,
/// `SOME (…)`.
///
/// This once reached execution. The walk hand-rolled its own recursion over the
/// expression variants that can carry a plan, listing `ScalarSubquery`,
/// `InSubquery` and `Exists` — three of the four DataFusion actually has. The
/// missing `Expr::SetComparison` blinded *both* the pre-gate (which then skipped
/// the rewrite for the whole plan) and the walk itself. Path A handled the same
/// query fine, which was the tell: the limitation was in the recursion, not the
/// query shape. Both now delegate to DataFusion's own traversal.
async
/// The `ANY` spelling of the same hole, so a fix that special-cases `ALL`
/// doesn't look green.
async
// ---------------------------------------------------------------------------
// Nodes that derive their output field names from their expressions.
// ---------------------------------------------------------------------------
/// `SELECT DISTINCT ON (…) grad(…)` must not rename the output field, or the
/// parent that refers to it by name dangles.
///
/// The analyzer aliases a rewritten expression back to its original
/// `schema_name` so a parent's column reference keeps resolving. That decision
/// was once made from a list of node variants — `Projection | Aggregate |
/// Window` — which omitted `Distinct::On`, whose schema is also derived from its
/// expressions. The field silently became `t.x + t.x` and the enclosing
/// projection dangled: the identical failure mode the alias-back exists to
/// prevent, one variant later. It is now derived from the node's own schema, so
/// a node kind nobody anticipated is handled by construction.
async
// ---------------------------------------------------------------------------
// A user's own UDF surviving into the derivative.
// ---------------------------------------------------------------------------
/// A UDF the user registered on their own `SessionContext`, appearing in the
/// *body* of a marker as a constant coefficient.
///
/// `d/dx [f(y) · x] = f(y)`, so `double_it(y)` survives verbatim into the
/// derivative. The re-plan registry was once seeded only from DataFusion's
/// built-ins, so `SqlToRel` could not resolve it and planning failed with
/// `Invalid function 'double_it'` plus a "did you mean" guess at an unrelated
/// built-in — naming neither the cause nor the remedy. Fixed by harvesting the
/// UDFs from the marker's own arguments, which needs no registration step and
/// works whenever the function was registered.
///
/// `DdxAnalyzer::with_engine_and_functions` remains the escape hatch, but only
/// for a function that appears in the derivative *without* appearing in the
/// body — which means a UDF emitted by a custom differentiation rule. Nothing
/// the user merely calls needs declaring.
async
// ---------------------------------------------------------------------------
// Recursive CTEs — a capability the docs once denied Path B had.
// ---------------------------------------------------------------------------
/// `lib.rs` tells users to "Reach for [`ddx_sql`] when the marker sits
/// somewhere a bound plan can't carry it — **most importantly inside a
/// recursive CTE**, which is exactly where a whole training loop lives."
///
/// Path B handles it. `LogicalPlan::RecursiveQuery` is in `inputs()`, so
/// `transform_up` walks both terms like any other node. This test passes today
/// and pins that, so the sole concrete justification offered for Path A can be
/// corrected rather than repeated.
///
/// (The shape that *looks* like a failure — `WITH RECURSIVE r(n) AS (SELECT
/// 1.0 UNION ALL …)` — fails identically with the derivative written out by
/// hand on a context with no ddx installed. It is DataFusion's own column
/// naming for an unaliased literal in a recursive term, nothing to do with ddx.)
async
// ---------------------------------------------------------------------------
// Where Path A and Path B legitimately disagree about a valid `wrt`.
// ---------------------------------------------------------------------------
/// `grad(sum(x)*sum(x), sum(x))`: Path B answers `12`, Path A refuses.
///
/// Neither behaviour is obviously wrong — by the time Path B sees the plan the
/// aggregate has already become the bound column `sum(t.x)`, so `2·sum(x)` is a
/// perfectly good answer to a question Path A cannot even parse as legal. What
/// *is* wrong is that nothing says so. `lib.rs` presents the two as "the same
/// rewrite by two routes" and lists their differences in a table that does not
/// mention this one, and `regressions.rs` installs
/// `path_a_and_path_b_agree_on_every_regression_case` as a standing guard
/// against exactly this drift.
///
/// The divergence is deliberate and documented rather than reconciled. Forcing
/// the two paths to agree would be the wrong fix:
///
/// * Path B's answer is correct. `sum(x)` over `[1,2,3]` is 6, and `d/ds(s·s)`
/// at `s = 6` is 12.
/// * Rejecting it would contradict a case ddx already accepts: differentiating
/// with respect to a *computed alias* is supported and correct — `grad(s*s, s)`
/// is `2s`. An aggregate output as the `wrt` is that same shape one level down.
/// * Detecting "this column is planner-derived" in order to refuse it would be
/// fragile, and would take the computed-alias case down with it.
///
/// So the rule is stated instead: Path B's `wrt` is any column of the node's
/// input schema, including planner-derived ones. See the "Where the two paths
/// genuinely differ" section of `lib.rs`.
async
// ---------------------------------------------------------------------------
// Correlated outer references: the one shape Path B genuinely cannot carry.
// ---------------------------------------------------------------------------
/// The bridge unparses a bound `Expr` to text and re-plans it against the
/// node's input schema. `Expr::OuterReferenceColumn` does not survive that
/// round trip: it unparses to an ordinary qualified column, which by
/// construction is not in the inner schema, so the user is told their column
/// does not exist.
///
/// Today: `ddx_markers caused by Schema error: No field named t.x. Valid fields
/// are u.x, u.y.` — a true statement about the wrong thing. Failing loudly is
/// right — ddx never guesses; blaming the user's column is not. The message
/// must name the real constraint, the way `get_table_source` in `replan.rs`
/// already does for its own unreachable case.
async
// ---------------------------------------------------------------------------
// A fact-check on a load-bearing code comment.
// ---------------------------------------------------------------------------
/// `replan.rs` justifies building — and throwing away — an entire
/// `SessionState` with: "`SessionStateDefaults::default_expr_planners()` would
/// say this directly but is private, so the list is borrowed from a throwaway
/// default state."
///
/// It is public. This test compiles, which is the proof. The throwaway
/// `SessionState` (catalog list, runtime env, object-store registry, every
/// function registry) exists to obtain a `Vec<Arc<dyn ExprPlanner>>` that one
/// public call returns.
///
/// This one passes today. It fails the day DataFusion actually makes the
/// function private — which is the signal that would justify the workaround.