Skip to content

fix: type scoring columns in projection expressions - #8163

Merged
Xuanwo merged 5 commits into
mainfrom
gatekeeper/fix-4712-1
Aug 3, 2026
Merged

Xuanwo merged 5 commits into
mainfrom
gatekeeper/fix-4712-1

Conversation

@lance-gatekeeper

@lance-gatekeeper lance-gatekeeper Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • preserve exact nullable Float32 _distance and _score placeholders during initial expression discovery, including beside legal mixed-case stored columns
  • carry case-insensitive stored scoring-column matches into physical projection while deferring final scoring-expression resolution to the actual input schema
  • preserve stored scoring names and types while generated search fields remain Float32, with coverage for absent, colliding, mixed-case, and schema-dependent function expressions

Root cause

Projection expressions are initially parsed before search operators add their generated scoring columns. Schema-dependent functions resolve arguments during this first parse, so scoring identifiers need exact provisional bindings before references can be detected. Omitting a placeholder when a mixed-case stored field exists makes function parsing fail case-sensitively, while keeping the placeholder without carrying the stored field forward breaks ordinary case-insensitive projections.

The discovery schema now retains exact generated-name placeholders without duplicating exact stored names. Matching mixed-case stored fields are separately included in the physical projection, and scoring expressions are reparsed against the actual physical input schema. Ordinary projections therefore preserve stored names and types, while search projections bind generated lowercase Float32 fields.

Validation

  • cargo fmt --all
  • cargo test -p lance-datafusion --locked
  • cargo clippy --all --tests --benches -- -D warnings

Fixes #4712

@github-actions github-actions Bot added the bug Something isn't working label Aug 3, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate recommendation: request changes. The scoring fields do need to participate in early coercion, but the planning schema must remain valid for datasets that already contain these legal column names. Prefer a collision-safe, search-aware planning schema that supplies generated Float32 types without changing ordinary stored-column projection behavior.

Comment thread rust/lance-datafusion/src/projection.rs Outdated
));
// Search operators add these columns after projection planning. Their types must be
// available here so expressions that reference them are coerced before physical planning.
fields.push(Arc::new(ArrowField::new(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These scoring names are not reserved at write time, so a dataset can already contain _distance or _score. Appending another field with the same name makes Schema::try_from reject the entire planner schema; as a result, even an unrelated non-search expression such as id + 1 now fails. Build the search-aware planning schema without duplicate names and preserve the stored field type outside a search (or defer/replan coercion against the actual search schema).

Reproducer
#[test]
fn test_stored_scoring_column_does_not_break_other_expressions() {
    for scoring_column in ["_distance", "_score"] {
        let base = Arc::new(
            Schema::try_from(&ArrowSchema::new(vec![
                ArrowField::new("id", DataType::Int64, false),
                ArrowField::new(scoring_column, DataType::Float64, true),
            ]))
            .unwrap(),
        );

        ProjectionPlan::from_expressions(base, &[("incremented", "id + 1")]).unwrap();
    }
}

cargo test -p lance-datafusion test_stored_scoring_column_does_not_break_other_expressions --locked passes on 4364f07d and fails on this head with Duplicate field name "_distance".

@codecov

codecov Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
rust/lance-datafusion/src/projection.rs 95.65% 0 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate recommendation: request changes. Replanning against the physical input schema is the right direction and fixes the stored-name collision, but the deferral decision must occur before schema-dependent SQL parsing. Make scoring fields available only for initial expression discovery—or inspect raw SQL first—then retain the final-schema reparse so generated and stored scoring columns remain correctly typed.

// (which DataFusion's physical evaluator expects to have been rewritten
// into a `CASE` expression by the simplifier) work correctly.
let expr = self.planner.optimize_expr(expr)?;
let expr = if Self::references_scoring_column(&expr) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferral is decided only after parse_expr, but schema-dependent functions resolve their arguments during that first parse. On the usual search schema, which has no stored scoring field yet, coalesce(1 - _distance, 0) therefore fails with No field named _distance before references_scoring_column can run. Since generated scoring fields are nullable, this excludes an important projection pattern. Add collision-safe provisional scoring fields only when missing (which also enables case-insensitive resolution), or detect raw SQL references before schema resolution, then keep the final-schema reparse.

Reproducer
#[test]
fn test_scoring_column_function_expression() {
    for scoring_column in ["_distance", "_score"] {
        let expression = format!("coalesce(1 - {scoring_column}, 0)");
        let plan = ProjectionPlan::from_expressions(
            Arc::new(Schema::default()),
            &[("normalized", expression.as_str())],
        )
        .unwrap();
        let batch = RecordBatch::try_from_iter([(
            scoring_column,
            Arc::new(Float32Array::from(vec![Some(0.25), None])) as ArrayRef,
        )])
        .unwrap();

        let physical_exprs = plan.to_physical_exprs(batch.schema().as_ref()).unwrap();
        let values = physical_exprs[0]
            .0
            .evaluate(&batch)
            .unwrap()
            .into_array(batch.num_rows())
            .unwrap();
        assert_eq!(values.as_ref(), &Float32Array::from(vec![0.75, 0.0]));
    }
}

cargo test -p lance-datafusion test_scoring_column_function_expression --locked fails on this head during from_expressions with Error parsing function: ... No field named _distance.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate recommendation: request changes. The provisional scoring schema now handles the original duplicate-name and early-coercion failures, but it must preserve Lance's case-insensitive stored-column resolution. Treat scoring-name collision detection, reference detection, and final replanning consistently so ordinary projections still load legal mixed-case stored fields while search projections resolve generated fields from their physical schema.

// fields keep their own types here; scoring expressions are replanned against the final
// physical schema before execution.
for name in ["_distance", "_score"] {
if schema.field_with_name(name).is_err() {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This exact-name check can add synthetic _distance beside a legal stored _Distance. Since Planner resolves column names case-insensitively, an ordinary _distance projection then binds to the synthetic exact name during discovery, records no stored physical column, and fails when the output schema is built. Make provisional collision detection and scoring-reference detection use the same case-insensitive rule, preserving the resolved stored field for physical projection and final-schema replanning.

Reproducer
#[test]
fn test_stored_scoring_column_is_case_insensitive() {
    let base = Arc::new(
        Schema::try_from(&ArrowSchema::new(vec![ArrowField::new(
            "_Distance",
            DataType::Float64,
            true,
        )]))
        .unwrap(),
    );
    let plan =
        ProjectionPlan::from_expressions(base, &[("stored", "_distance")]).unwrap();

    assert_eq!(
        plan.output_schema().unwrap().field(0).data_type(),
        &DataType::Float64,
    );
}

cargo test -p lance-datafusion test_stored_scoring_column_is_case_insensitive --locked passes on base 4364f07d and fails on this head with FieldNotFound { field: "_distance", valid_fields: [] }.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate recommendation: request changes. The stored mixed-case regression is fixed, but scoring-name resolution still must happen before schema-dependent function parsing. Preserve a provisional generated-name binding through discovery—or canonicalize scoring identifiers in the raw expression—then keep final-schema replanning so searches can distinguish generated Float32 fields from legal mixed-case stored fields.

Comment thread rust/lance-datafusion/src/projection.rs Outdated
let has_stored_column = schema
.fields()
.iter()
.any(|field| canonical_scoring_column(field.name()) == Some(name));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case-insensitive collision check removes provisional _distance when the dataset contains _Distance. A search expression such as coalesce(1 - _distance, 0) should ultimately bind the generated lowercase Float32 field, but initial DataFusion function parsing sees only _Distance and fails case-sensitively before references_scoring_column can canonicalize it. Normalize scoring identifiers in the raw SQL/AST before parsing, or retain the exact provisional binding while separately carrying the matching stored field into physical projection; final-schema replanning can then disambiguate them.

Reproducer
#[test]
fn test_generated_scoring_function_with_mixed_case_stored_column() {
    let base = Arc::new(
        Schema::try_from(&ArrowSchema::new(vec![ArrowField::new(
            "_Distance",
            DataType::Float64,
            true,
        )]))
        .unwrap(),
    );
    let plan = ProjectionPlan::from_expressions(
        base,
        &[("normalized", "coalesce(1 - _distance, 0)")],
    )
    .unwrap();
    let batch = RecordBatch::try_from_iter([(
        "_distance",
        Arc::new(Float32Array::from(vec![Some(0.25), None])) as ArrayRef,
    )])
    .unwrap();

    plan.to_physical_exprs(batch.schema().as_ref()).unwrap();
}

cargo test -p lance-datafusion test_generated_scoring_function_with_mixed_case_stored_column --locked fails on cbd928dc during from_expressions with No field named _distance ... Did you mean '_Distance'?.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate recommendation: approve. The revised discovery path keeps exact scoring placeholders for schema-dependent parsing, carries legal stored matches into physical projection, and replans against the final input schema. This preserves stored field names and types while selecting generated Float32 scoring fields during search.

@Xuanwo
Xuanwo merged commit 951f129 into main Aug 3, 2026
39 of 43 checks passed
@Xuanwo
Xuanwo deleted the gatekeeper/fix-4712-1 branch August 3, 2026 16:48
Xuanwo added a commit to lancedb/lancedb that referenced this pull request Aug 27, 2026
## Summary

- add Python regression coverage for integer and double arithmetic
against the generated _distance column
- merge the current main base containing Lance v11.0.0-beta.3 from #3896
- verify both expressions retain the generated scoring field Float32
type and compute the expected values

## Root cause

Lance parsed dynamic projection expressions before vector search added
its generated Float32 _distance field. Without a typed provisional
field, expression discovery rejected mixed numeric arithmetic. Lance
upstream fixed discovery and final-schema replanning in
lance-format/lance#8163, and the current base consumes that fix through
Lance v11.0.0-beta.3.

## Validation

- uv run --extra tests pytest
python/tests/test_query.py::test_select_arithmetic_with_distance -vv
--maxfail=2 — 2 passed
- python/.venv/bin/ruff format --check python/python/tests/test_query.py
- python/.venv/bin/ruff check .

Fixes #2618

<!-- lance-gatekeeper-fix:v1 agent=816a060090517471edfb73652bb5c9fe
generation=1 -->

---------

Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com>
Co-authored-by: Xuanwo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Projecting with _distance column gives type mismatch error

1 participant