fix: allow matched merge updates to Function inputs (#5062)

Matched merge-insert updates rejected every non-key source column that a
Function binding reads, while update already accepts input changes and
the merge freshness path records their changed signatures. Use the same
`ensure_not_written` guard for the matched source columns: inputs pass,
computed outputs and assignment columns stay rejected before any write,
and insert-only or unrelated-column merges keep their behavior.

Regressions confirm a matched input update retains prior outputs,
dirties only the affected rows, keeps an independent binding fresh, and
rejects mixed input/output sources without committing.

Tested on `2ab103d7` + this change: `cargo test -p lancedb --lib` 1083
passed, 82 ignored.

Refs ENT-3515
This commit is contained in:
Xuanwo
2026-11-16 20:23:25 +08:00
committed by GitHub
parent d475005592
commit 3b7c4dcf66
2 changed files with 180 additions and 18 deletions
+130
View File
@@ -3248,6 +3248,136 @@ mod tests {
}
}
#[tokio::test]
async fn input_merge_dirties_only_the_updated_rows_and_retains_outputs() {
let table = fresh_function_table().await;
let source =
arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"]))
.unwrap();
let mut merge = table.merge_insert(&["title"]);
merge.when_matched_update_all(None);
let result = merge
.execute(Box::new(RecordBatchIterator::new(
[Ok(source.clone())],
source.schema(),
)))
.await
.unwrap();
assert_eq!(result.num_updated_rows, 1);
let dataset = table.as_native().unwrap().dataset.get().await.unwrap();
for output in ["search_text", "search_token_count"] {
let stale = function_plan(&dataset, output).await;
let mut dirty_rows = 0;
for fragment in dataset.get_fragments() {
if stale.needs_recompute(fragment.id() as u32) {
let batch = fragment
.scan()
.project(&["title"])
.unwrap()
.try_into_batch()
.await
.unwrap();
let titles = batch
.column(0)
.as_any()
.downcast_ref::<arrow_array::StringArray>()
.unwrap();
assert!(titles.iter().all(|title| title == Some("a")), "{stale:?}");
dirty_rows += batch.num_rows();
}
}
assert_eq!(dirty_rows, 1, "{stale:?}");
}
assert_eq!(table.count_rows(Some("title = 'a' AND body = 'changed' AND search_text = 'a x' AND search_token_count = 2".into())).await.unwrap(), 1);
}
#[tokio::test]
async fn input_merge_keeps_an_independent_function_binding_fresh() {
let batch = arrow_array::record_batch!(
("title", Utf8, ["a", "b", "c", "d"]),
("body", Utf8, ["x", "y", "z", "w"]),
("search_text", Utf8, ["a x", "b y", "c z", "d w"]),
("search_token_count", Int64, [2, 2, 2, 2]),
("search_text_other", Utf8, ["a a", "b b", "c c", "d d"]),
("search_token_count_other", Int64, [2, 2, 2, 2])
)
.unwrap();
let table = crate::connect("memory://")
.execute()
.await
.unwrap()
.create_table("independent_merge", batch)
.write_options(crate::table::WriteOptions {
lance_write_params: Some(WriteParams {
max_rows_per_file: 2,
..Default::default()
}),
})
.execute()
.await
.unwrap();
let mut other = serde_json::to_value(text_features_binding("_other")).unwrap();
other["inputs"][1]["field_path"] = serde_json::json!("title");
other["inputs"][1]["field_id"] = other["inputs"][0]["field_id"].clone();
let bindings = [
text_features_binding(""),
serde_json::from_value(other).unwrap(),
];
stamp_bindings(&table, &bindings).await;
let native = table.as_native().unwrap();
let mut dataset = native.dataset.get().await.unwrap().as_ref().clone();
for binding in &bindings {
let paths = binding
.inputs()
.iter()
.map(|input| input.field_path.clone())
.collect::<Vec<_>>();
let inputs = fields_for_paths(dataset.schema(), &paths).unwrap();
let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap();
for output in binding.outputs() {
write_signatures(
&mut dataset,
&output.output_name,
binding.binding_id(),
signatures.clone(),
)
.await
.unwrap();
}
}
native.dataset.update(dataset);
let source =
arrow_array::record_batch!(("title", Utf8, ["a"]), ("body", Utf8, ["changed"]))
.unwrap();
let mut merge = table.merge_insert(&["title"]);
merge.when_matched_update_all(None);
merge
.execute(Box::new(RecordBatchIterator::new(
[Ok(source.clone())],
source.schema(),
)))
.await
.unwrap();
let dataset = native.dataset.get().await.unwrap();
assert!(
function_plan(&dataset, "search_text")
.await
.needs_recompute(2)
);
let other = &bindings[1];
let inputs = fields_for_paths(dataset.schema(), &["title".into()]).unwrap();
for output in other.outputs() {
let stale =
staleness_against(&dataset, &output.output_name, other.binding_id(), &inputs)
.await
.unwrap();
assert!(
!stale.recompute_all && stale.dirty.is_empty() && stale.row_dirty.is_empty(),
"{stale:?}"
);
}
}
#[rstest::rstest]
#[case::same_definition(false)]
#[case::changed_definition(true)]
+50 -18
View File
@@ -249,11 +249,13 @@ impl MergeInsertBuilder {
Ok(())
}
/// The existing columns a matched row takes from `source`: every source
/// column but the join keys, which a match leaves equal. An insert-only
/// merge rewrites none; its new rows get Function outputs from the next
/// refresh, as appended rows do.
pub(crate) fn function_guarded_columns(&self, source: &Fields) -> Vec<String> {
/// The source columns a matched row writes: every column but the join
/// keys, which a match leaves equal. Function inputs stay writable; the
/// merge records their changed signatures so the next refresh recomputes
/// the affected rows. Computed outputs and assignment columns remain
/// protected by the direct-write guard. An insert-only merge writes none;
/// its new rows get Function outputs from the next refresh.
pub(crate) fn matched_source_columns(&self, source: &Fields) -> Vec<String> {
if !self.when_matched_update_all {
return Vec::new();
}
@@ -351,10 +353,10 @@ pub(crate) async fn execute_merge_insert(
) -> Result<MergeResult> {
params.canonicalize_filters()?;
let schema = table.schema().await?;
super::computed_columns::ensure_not_function_bound(
let matched_columns = params.matched_source_columns(new_data.schema().fields());
super::computed_columns::ensure_not_written(
schema.as_ref(),
"merge_insert",
params.function_guarded_columns(new_data.schema().fields()),
matched_columns.iter().map(String::as_str),
)?;
// Normalize blob layouts and JSON extension metadata just as on append.
// Keep arrow.json text labelled until Lance encodes it as JSONB.
@@ -970,10 +972,11 @@ mod tests {
assert_eq!(table.count_rows(None).await.unwrap(), 2);
}
/// A matched row takes every non-key source column, so the merge is
/// refused only when one of those is a binding's input or output.
/// A matched row takes every non-key source column. Function inputs are
/// writable and become stale for the next refresh; computed outputs stay
/// protected, and a mixed input/output source is rejected before commit.
#[tokio::test]
async fn merge_update_on_a_function_table_refuses_only_bound_columns() {
async fn merge_update_allows_function_inputs_but_protects_outputs() {
let table = crate::table::computed_columns::test_support::bound_table_from(
arrow_array::record_batch!(
("id", Int32, [1]),
@@ -998,18 +1001,47 @@ mod tests {
let mut merge = table.merge_insert(&["id"]);
merge.when_matched_update_all(None);
let err = merge
let result = merge
.execute(reader(
arrow_array::record_batch!(("id", Int32, [1]), ("title", Utf8, ["z"])).unwrap(),
))
.await
.unwrap_err();
assert!(
matches!(&err, crate::Error::InvalidInput { message }
if message.contains("merge_insert of 'title'")
&& message.contains("a Function binding reads or writes it")),
"{err:?}"
.unwrap();
assert_eq!(result.num_updated_rows, 1);
assert_eq!(
table
.count_rows(Some("title = 'z' AND search_text = 'a b'".into()))
.await
.unwrap(),
1
);
let version = table.version().await.unwrap();
for source in [
arrow_array::record_batch!(("id", Int32, [1]), ("search_text", Utf8, ["uncomputed"]))
.unwrap(),
arrow_array::record_batch!(
("id", Int32, [1]),
("title", Utf8, ["must not commit"]),
("search_text", Utf8, ["uncomputed"])
)
.unwrap(),
] {
let mut merge = table.merge_insert(&["id"]);
merge.when_matched_update_all(None);
let err = merge.execute(reader(source)).await.unwrap_err();
assert!(
matches!(&err, crate::Error::InvalidInput { message }
if message.contains("is computed")
&& message.contains("cannot be written directly")),
"{err:?}"
);
assert_eq!(table.version().await.unwrap(), version);
assert_eq!(
table.count_rows(Some("title = 'z'".into())).await.unwrap(),
1
);
}
}
}