Skip to content

Commit 00a55b0

Browse files
alxmrsclaude
andcommitted
fix(ddx-ad): read DuckDB's one-argument subtract as negate
DuckDB's Substrait producer writes unary minus as `subtract` with one argument, declared as a bare `subtract`, where Substrait's function is `negate`. ddx's rules match a two-argument subtract and a one-argument negate, so `SELECT SUM(-v) FROM w` was refused on DuckDB: no differentiation rule for `subtract`. in_read_form now points each one-argument call to a subtract, in a plan whose producer is DuckDB, at a new declaration of `negate`. It runs after windows become projections, so a negation in a window function's argument is reached too. Fixes #262. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CvszJhH8pn8H9G69wEPMU2
1 parent afaaf3a commit 00a55b0

2 files changed

Lines changed: 123 additions & 2 deletions

File tree

‎crates/ddx-ad/src/forward.rs‎

Lines changed: 110 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
//! a refusal that is raised only if gradient actually reaches it.
4040
4141
use std::borrow::Cow;
42-
use std::collections::{BTreeSet, HashMap};
42+
use std::collections::{BTreeSet, HashMap, HashSet};
4343
use std::ops::ControlFlow;
4444
use std::rc::Rc;
4545

@@ -48,6 +48,8 @@ use prost::Message;
4848
use substrait::proto::aggregate_rel::Grouping;
4949
use substrait::proto::expression::mask_expression::{StructItem, StructSelect};
5050
use substrait::proto::expression::{MaskExpression, RexType, WindowFunction};
51+
use substrait::proto::extensions::simple_extension_declaration::{ExtensionFunction, MappingType};
52+
use substrait::proto::extensions::SimpleExtensionDeclaration;
5153
use substrait::proto::function_argument::ArgType;
5254
use substrait::proto::join_rel::JoinType;
5355
use substrait::proto::plan_rel::RelType as PlanRelType;
@@ -625,6 +627,9 @@ fn two(widths: &[Option<usize>]) -> Result<Option<(usize, usize)>> {
625627
/// where Substrait reads every column, so each field after it would land
626628
/// on the wrong column. Such a read gets a mask of the table's first
627629
/// column, which nothing reads.
630+
/// - **DuckDB's unary minus.** DuckDB's producer writes `-x` as `subtract`
631+
/// with one argument, where Substrait's is `negate`. Such a call is
632+
/// pointed at a declaration of `negate`.
628633
pub(crate) fn in_read_form(plan: &Plan) -> Cow<'_, Plan> {
629634
let duckdb = plan
630635
.version
@@ -635,7 +640,19 @@ pub(crate) fn in_read_form(plan: &Plan) -> Cow<'_, Plan> {
635640
RelType::Read(r) => duckdb && reads_no_columns(r),
636641
_ => false,
637642
};
638-
if !PlanRels.then(Deep).then(RelKind).any(plan, changes) {
643+
let subtracts: HashSet<u32> = if duckdb {
644+
function_anchors(plan, "subtract").collect()
645+
} else {
646+
HashSet::new()
647+
};
648+
let negation = |e: &Expression| match &e.rex_type {
649+
Some(RexType::ScalarFunction(f)) => {
650+
f.arguments.len() == 1 && subtracts.contains(&f.function_reference)
651+
}
652+
_ => false,
653+
};
654+
let exprs = || PlanRels.then(Deep).then(RelKind).then(Exprs).then(Cosmos);
655+
if !PlanRels.then(Deep).then(RelKind).any(plan, changes) && !exprs().any(plan, negation) {
639656
return Cow::Borrowed(plan);
640657
}
641658
let mut plan = plan.clone();
@@ -659,9 +676,57 @@ pub(crate) fn in_read_form(plan: &Plan) -> Cow<'_, Plan> {
659676
}
660677
_ => {}
661678
});
679+
// After the windows are projections, whose expressions `Exprs` reaches.
680+
if exprs().any(&plan, negation) {
681+
let negate = declare_function(&mut plan, "negate");
682+
exprs().modify(&mut plan, |e| {
683+
if negation(e) {
684+
if let Some(RexType::ScalarFunction(f)) = &mut e.rex_type {
685+
f.function_reference = negate;
686+
}
687+
}
688+
});
689+
}
662690
Cow::Owned(plan)
663691
}
664692

693+
/// The anchors of `plan`'s declarations of the function `name`, whatever
694+
/// their signatures.
695+
fn function_anchors<'a>(plan: &'a Plan, name: &'a str) -> impl Iterator<Item = u32> + 'a {
696+
plan.extensions
697+
.iter()
698+
.filter_map(move |d| match &d.mapping_type {
699+
Some(MappingType::ExtensionFunction(f))
700+
if crate::functions::normalize(&f.name) == name =>
701+
{
702+
Some(f.function_anchor)
703+
}
704+
_ => None,
705+
})
706+
}
707+
708+
/// A new declaration of the function `name` in `plan`, at the anchor after
709+
/// its last function's, with no extension URN, as DuckDB declares its own.
710+
fn declare_function(plan: &mut Plan, name: &str) -> u32 {
711+
let anchor = plan
712+
.extensions
713+
.iter()
714+
.filter_map(|d| match &d.mapping_type {
715+
Some(MappingType::ExtensionFunction(f)) => Some(f.function_anchor + 1),
716+
_ => None,
717+
})
718+
.max()
719+
.unwrap_or(0);
720+
plan.extensions.push(SimpleExtensionDeclaration {
721+
mapping_type: Some(MappingType::ExtensionFunction(ExtensionFunction {
722+
function_anchor: anchor,
723+
name: name.into(),
724+
..Default::default()
725+
})),
726+
});
727+
anchor
728+
}
729+
665730
/// Does DuckDB's producer mean `r` to read none of its table's columns: a
666731
/// read with no mask, of a table that has some.
667732
fn reads_no_columns(r: &ReadRel) -> bool {
@@ -2465,6 +2530,49 @@ mod tests {
24652530
assert_eq!(masks, [Some(first), Some(mask)]);
24662531
}
24672532

2533+
#[test]
2534+
fn duckdb_s_one_argument_subtract_is_read_as_negate() {
2535+
// DuckDB's `SELECT -v, v - v FROM t`: its unary minus is declared
2536+
// as a bare `subtract`, at its own anchor.
2537+
let declare = |anchor, name: &str| SimpleExtensionDeclaration {
2538+
mapping_type: Some(MappingType::ExtensionFunction(ExtensionFunction {
2539+
function_anchor: anchor,
2540+
name: name.into(),
2541+
..Default::default()
2542+
})),
2543+
};
2544+
let exprs = vec![
2545+
crate::expr::call(1, vec![field(0)]),
2546+
crate::expr::call(3, vec![field(0), field(0)]),
2547+
];
2548+
let read = emit::read_step("t", vec!["v".into()]);
2549+
let functions = Functions::from_plan(&Plan::default()).unwrap();
2550+
let ext = crate::functions::Extensions::new(&functions);
2551+
let mut plan = emit::plan(
2552+
emit::project_emit(read, exprs, Some(vec![1, 2])),
2553+
vec!["n".into(), "d".into()],
2554+
&ext,
2555+
);
2556+
plan.extensions = vec![declare(1, "subtract"), declare(3, "subtract:fp64_fp64")];
2557+
assert!(matches!(in_read_form(&plan), Cow::Borrowed(_)));
2558+
plan.version = Some(substrait::version::version_with_producer("DuckDB"));
2559+
let read = in_read_form(&plan);
2560+
let functions = Functions::from_plan(&read).unwrap();
2561+
let (root, _) = root_of(&read).unwrap();
2562+
let Some(RelType::Project(p)) = &root.rel_type else {
2563+
panic!("{root:?}")
2564+
};
2565+
let names: Vec<_> = p
2566+
.expressions
2567+
.iter()
2568+
.map(|e| match &e.rex_type {
2569+
Some(RexType::ScalarFunction(f)) => functions.name(f.function_reference).unwrap(),
2570+
other => panic!("{other:?}"),
2571+
})
2572+
.collect();
2573+
assert_eq!(names, ["negate", "subtract"]);
2574+
}
2575+
24682576
#[test]
24692577
fn a_namespace_separates_its_clock_from_its_counter() {
24702578
// Without a separator, clock 0xabc1 with counter 2 and clock 0xabc

‎python/ddxdb/tests/test_duckdb.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,19 @@ def test_a_table_read_for_its_rows_alone_keeps_the_columns_after_it(tables, loss
252252
assert con.sql(program.gradients[0].query()).fetchall() == [(0, gradient)]
253253

254254

255+
@pytest.mark.parametrize(
256+
"loss, gradient",
257+
[
258+
("SELECT SUM(-val) AS l FROM w", [(0, -1.0), (1, -1.0), (2, -1.0)]),
259+
("SELECT SUM(-(-val) * val) AS l FROM w", [(0, 2.0), (1, -4.0), (2, 1.0)]),
260+
("SELECT SUM(s) AS l FROM (SELECT -SUM(val) OVER (ORDER BY i) AS s FROM w)", [(0, -3.0), (1, -2.0), (2, -1.0)]),
261+
],
262+
)
263+
def test_unary_minus_is_differentiated(ad, con, loss, gradient):
264+
# DuckDB writes `-x` as a one-argument subtract (#262).
265+
assert pairs(ad.sql(con, f"WITH loss AS ({loss}) SELECT i, grad(loss, val) FROM w")) == gradient
266+
267+
255268
def test_grad_in_sql_is_a_column_of_its_table_s_rows(ad, con):
256269
assert pairs(ad.sql(con, GRAD)) == [(0, 3.0), (1, 12.0), (2, 0.75)]
257270

0 commit comments

Comments
 (0)