From d93d82d262407b6742e54458ccfca8d7a76c8c7c Mon Sep 17 00:00:00 2001 From: Sergey Date: Mon, 30 Nov 2026 21:11:18 +0100 Subject: [PATCH 1/4] fix: allow legacy ndarray shape in mypy check --- integration_tests/db_connectors/test_mongodb_nested_schema.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/integration_tests/db_connectors/test_mongodb_nested_schema.py b/integration_tests/db_connectors/test_mongodb_nested_schema.py index 64fdf2762..c75b7d009 100644 --- a/integration_tests/db_connectors/test_mongodb_nested_schema.py +++ b/integration_tests/db_connectors/test_mongodb_nested_schema.py @@ -92,7 +92,8 @@ def read_collection(schema, collection): pytest.param(INT_ARRAY, [], np.array([], dtype=np.int64), id="empty-array"), pytest.param(INT_ARRAY, 7, np.array([7]), id="scalar-as-vector"), pytest.param( - np.ndarray[None, np.dtype[np.int64]], + # Pathway supports None for unknown rank; NumPy 2 stubs require a tuple. + np.ndarray[None, np.dtype[np.int64]], # type: ignore[type-var, unused-ignore] [[[1, 2]]], np.array([[[1, 2]]]), id="unknown-rank", From f7b0eb7aaa1414bb1a17829b1aa2b00c1eb6e931 Mon Sep 17 00:00:00 2001 From: Sergey Date: Mon, 30 Nov 2026 21:53:21 +0100 Subject: [PATCH 2/4] test: skip licensed examples when no key is available --- python/pathway/conftest.py | 7 +++++++ python/pathway/io/mysql/__init__.py | 1 + python/pathway/tests/test_nested_lake_schema.py | 2 +- python/pathway/tests/test_nested_schema_docs.py | 12 +++++++++++- 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/python/pathway/conftest.py b/python/pathway/conftest.py index d7dd6ba62..3a853c17f 100644 --- a/python/pathway/conftest.py +++ b/python/pathway/conftest.py @@ -59,6 +59,13 @@ def requires_license() -> None: """Require a configured license key for a test or doctest.""" +@pytest.fixture +def skip_without_license() -> None: + """Skip a test or doctest when licensed features cannot be exercised.""" + if not config.get_pathway_config().license_key: + pytest.skip("requires a Pathway license key") + + environment_stash_key = pytest.StashKey[dict[str, str]]() diff --git a/python/pathway/io/mysql/__init__.py b/python/pathway/io/mysql/__init__.py index 0687335c6..90d3bb4d5 100644 --- a/python/pathway/io/mysql/__init__.py +++ b/python/pathway/io/mysql/__init__.py @@ -195,6 +195,7 @@ def read( ``{"price": 12.5, "content": "AQI="}``. Bytes inside the JSON value use base64, even when the database also supports native binary columns. + >>> getfixture("skip_without_license") # NODOCS >>> import pathway as pw >>> class Payload(pw.Schema): ... price: float diff --git a/python/pathway/tests/test_nested_lake_schema.py b/python/pathway/tests/test_nested_lake_schema.py index f72a51ed9..c53a2eae2 100644 --- a/python/pathway/tests/test_nested_lake_schema.py +++ b/python/pathway/tests/test_nested_lake_schema.py @@ -17,7 +17,7 @@ @pytest.fixture(params=[False, True], ids=["parquet", "arrow-backfill"]) -def lake_reader(request, tmp_path): +def lake_reader(request, tmp_path, skip_without_license): def read(rows, arrow_type, schema): location = tmp_path / "lake" write_deltalake( diff --git a/python/pathway/tests/test_nested_schema_docs.py b/python/pathway/tests/test_nested_schema_docs.py index f3e51a8d2..aa4a41494 100644 --- a/python/pathway/tests/test_nested_schema_docs.py +++ b/python/pathway/tests/test_nested_schema_docs.py @@ -37,8 +37,18 @@ ) @pytest.mark.parametrize("clean_docstring", [False, True]) def test_nested_schema_read_docstring_example( - connector, clean_docstring, tmp_path, monkeypatch + connector, clean_docstring, tmp_path, monkeypatch, request ): + if connector in { + "deltalake", + "elasticsearch", + "kinesis", + "mssql", + "mysql", + "postgres", + "rabbitmq", + }: + request.getfixturevalue("skip_without_license") reader = getattr(pw.io, connector).read # Python 3.13+ can strip the common indentation when compiling docstrings. doc = inspect.cleandoc(reader.__doc__) if clean_docstring else reader.__doc__ From e8034c6a7f5d1cb7a7b09a3a1688552c525ff262 Mon Sep 17 00:00:00 2001 From: Sergey Date: Mon, 30 Nov 2026 22:26:33 +0100 Subject: [PATCH 3/4] fix: discard async results for superseded rows --- .../tests/test_fully_async_udf_updates.py | 146 ++++++++++++++++++ src/engine/dataflow/async_transformer.rs | 146 +++++++++++++++--- 2 files changed, 273 insertions(+), 19 deletions(-) create mode 100644 python/pathway/tests/test_fully_async_udf_updates.py diff --git a/python/pathway/tests/test_fully_async_udf_updates.py b/python/pathway/tests/test_fully_async_udf_updates.py new file mode 100644 index 000000000..443f509e8 --- /dev/null +++ b/python/pathway/tests/test_fully_async_udf_updates.py @@ -0,0 +1,146 @@ +# Copyright © 2026 Pathway + +import asyncio +import threading + +import pytest + +import pathway as pw +from pathway.internals import api +from pathway.internals.parse_graph import G + + +@pytest.mark.parametrize( + ("reinsert_same_value", "reinsert_before_completion", "same_batch_replacement"), + [ + (False, False, False), + (False, True, False), + (False, True, True), + (True, False, False), + (True, True, False), + ], +) +@pytest.mark.parametrize("as_transformer", [False, True]) +def test_fully_async_udf_keeps_results_for_the_current_input( + reinsert_before_completion, + reinsert_same_value, + same_batch_replacement, + as_transformer, +): + """A completed invocation must not revive or overwrite a deleted row.""" + old_started = threading.Event() + old_can_finish = threading.Event() + old_finished = threading.Event() + deletion_seen = threading.Event() + reinsertion_seen = threading.Event() + probe_seen = threading.Event() + new_can_finish = threading.Event() + outputs = [] + input_times = {} + new_value = 10 if reinsert_same_value else 12 + calls_for_ten = 0 + + class InputSchema(pw.Schema): + a: int + + class InputSubject(pw.io.python.ConnectorSubject): + def run(self): + self._add_inner(api.ref_scalar(3), {"a": 10}) + self.commit() + assert old_started.wait(10), "first UDF did not start" + if same_batch_replacement: + self._disable_commits() + self._remove_inner(api.ref_scalar(3), {"a": 10}) + if same_batch_replacement: + self._add_inner(api.ref_scalar(3), {"a": new_value}) + self._enable_commits() + self.commit() + assert deletion_seen.wait(10), "input deletion was not observed" + if reinsert_before_completion: + if not same_batch_replacement: + self._add_inner(api.ref_scalar(3), {"a": new_value}) + self.commit() + assert reinsertion_seen.wait(10), "input reinsertion was not observed" + old_can_finish.set() + assert old_finished.wait(10), "first UDF did not finish" + # A separate key observes progress through the async output stream. + self._add_inner(api.ref_scalar(4), {"a": 20}) + self.commit() + assert probe_seen.wait(10), "async output did not reach the probe" + if not reinsert_before_completion: + self._add_inner(api.ref_scalar(3), {"a": new_value}) + self.commit() + new_can_finish.set() + + async def compute_value(a: int) -> int: + nonlocal calls_for_ten + if a == 10: + calls_for_ten += 1 + if calls_for_ten == 1: + old_started.set() + assert await asyncio.to_thread(old_can_finish.wait, 10) + old_finished.set() + return 101 + assert await asyncio.to_thread(new_can_finish.wait, 10) + return 102 + if a == 12: + assert await asyncio.to_thread(new_can_finish.wait, 10) + return 1201 + return 2001 + + def observe_input(key, row, time, is_addition): + if key == api.ref_scalar(3): + if not is_addition: + input_times["deletion"] = time + deletion_seen.set() + elif deletion_seen.is_set(): + input_times["reinsertion"] = time + reinsertion_seen.set() + + def observe_output(key, row, time, is_addition): + outputs.append((key, row, is_addition)) + if key == api.ref_scalar(4) and is_addition: + probe_seen.set() + + table = pw.io.python.read( + InputSubject(), schema=InputSchema, autocommit_duration_ms=10 + ) + pw.io.subscribe(table, on_change=observe_input) + if as_transformer: + + class OutputSchema(pw.Schema): + result: int + + class Transformer(pw.AsyncTransformer, output_schema=OutputSchema): + async def invoke(self, a: int) -> dict[str, int]: + return {"result": await compute_value(a)} + + result = Transformer(table, autocommit_duration_ms=10).successful + else: + compute = pw.udf( + compute_value, + executor=pw.udfs.fully_async_executor(autocommit_duration_ms=10), + ) + result = table.select(a=table.a, result=compute(table.a)).await_futures() + pw.io.subscribe(result, on_change=observe_output) + try: + pw.run(monitoring_level=pw.MonitoringLevel.NONE) + finally: + G.clear() + + if same_batch_replacement: + assert input_times["deletion"] == input_times["reinsertion"] + expected_value = 102 if reinsert_same_value else 1201 + additions = [(key, row) for key, row, added in outputs if added] + assert any( + key == api.ref_scalar(3) and row["result"] == expected_value + for key, row in additions + ) + assert any( + key == api.ref_scalar(4) and row["result"] == 2001 for key, row in additions + ) + assert all( + key != api.ref_scalar(3) + or (row["result"] == expected_value and row.get("a", new_value) == new_value) + for key, row in additions + ), additions diff --git a/src/engine/dataflow/async_transformer.rs b/src/engine/dataflow/async_transformer.rs index e8b76a676..dc4c0d2d2 100644 --- a/src/engine/dataflow/async_transformer.rs +++ b/src/engine/dataflow/async_transformer.rs @@ -31,10 +31,11 @@ /// - extraction of a true row key and enriching the stream with input values from `values_currently_processed`. /// - creation of the forgetting stream using the key and input values retrieved earlier. /// The time is moved to the next retraction time so that it is easy to filter out forgetting entries later. +/// - discarding results whose task is no longer current for the input key. /// - grouping of the stream as batches (`consolidate_for_output`) -/// - keeping only the last entry (with greatest `seq_id`) for each key in each batch. -/// Having more entries for a single (key, time) pair would result in inconsistency in upserting later. -/// The final produced entry for some (key, time) pairs could not be the one with the greatest `seq_id`. +/// - keeping one entry for each key in each batch, preferring insertions over deletions +/// and then the greatest `seq_id`. Multiple entries for a (key, time) pair would make +/// the upsert inconsistent. /// - upsert operator with persistence. Upsert is there to avoid recomputation for deletions. Without upserting, /// there could be problems with inconsistency as the `AsyncTransformer` can be non-deterministic. /// Persistence is there to be able to update values computed in previous runs. @@ -47,6 +48,10 @@ use std::sync::Arc; use std::time::Duration; use differential_dataflow::input::InputSession; +use differential_dataflow::operators::arrange::upsert::arrange_from_upsert; +use differential_dataflow::operators::JoinCore; +use differential_dataflow::trace::implementations::ord::OrdValBatch; +use differential_dataflow::trace::implementations::spine_fueled::Spine; use differential_dataflow::{AsCollection, Collection}; use timely::dataflow::operators::{Exchange, Inspect, Map}; use timely::progress::Timestamp as _; @@ -63,8 +68,8 @@ use crate::engine::{ use super::maybe_total::MaybeTotalScope; use super::operators::output::ConsolidateForOutput; -use super::operators::{MapWrapped, MaybeTotal, Reshard}; -use super::{DataflowGraphInner, MaybePersist, Table, Tuple}; +use super::operators::{ArrangeWithTypes, MapWrapped, MaybeTotal, Reshard}; +use super::{ArrangedByKey, DataflowGraphInner, FilterOutForgetting, MaybePersist, Table, Tuple}; struct AsyncTransformerSession { input_session: InputSession, @@ -187,20 +192,22 @@ fn run_output_connector( graph: &mut DataflowGraphInner, table_handle: TableHandle, column_paths: Vec, - python_input_values: &Collection, + python_input_values: &Collection, mut callbacks: SubscribeCallbacks, values_currently_processed: Rc>>, skip_errors: bool, -) -> Result<()> +) -> Result> where S: MaybeTotalScope, { let forgetting_stream = python_input_values .inner - .map(move |((key, input_values, _values, _seq_id), time, diff)| { - // move time to retraction time so that it can be filtered out easily later - ((key, input_values), time.next_retraction_time(), diff) - }) + .map( + move |((key, input_values, _values, _sequence_and_task), time, diff)| { + // move time to retraction time so that it can be filtered out easily later + ((key, input_values), time.next_retraction_time(), diff) + }, + ) .as_collection() .negate(); @@ -211,10 +218,14 @@ where false, ))); + // The assigned task ids are also used to identify the current input + // generation, while the persisted input stream keeps its original format. + let assigned_requests = Rc::new(RefCell::new(None)); let logic = { let max_time_in_original_stream = max_time_in_original_stream.clone(); + let assigned_requests = assigned_requests.clone(); move |graph: &mut DataflowGraphInner, collection: Collection| { - Ok(collection + let assigned = collection .inner .exchange(|_data| 0) // Move all data to worker 0 to compute max time present in data. // Currently async transformer is run only on worker 0 so it is not a bottleneck. @@ -258,7 +269,9 @@ where None } }) - .as_collection()) + .as_collection(); + *assigned_requests.borrow_mut() = Some(assigned.clone()); + Ok(assigned) } }; @@ -290,7 +303,96 @@ where None, None, logic, - ) + )?; + let assigned = assigned_requests + .borrow_mut() + .take() + .expect("subscribe logic assigns task ids"); + Ok(assigned) +} + +fn keep_current_results( + assigned_requests: &Collection, + values: &Collection, +) -> Collection +where + S: MaybeTotalScope, +{ + // Track the most recent insertion for each input key. Unlike the + // completion stream, these events retain the original input timestamps. + // A same-batch replacement keeps its insertion, regardless of diff order. + let request_updates = assigned_requests + .consolidate_for_output(false) + .flat_map(|batch| { + let mut updates: HashMap> = HashMap::new(); + for ((key, tuple), diff) in batch.data { + if diff == 1 { + let task_id = tuple + .last() + .expect("assigned task id is present") + .as_pointer() + .expect("assigned task id is a pointer"); + updates.insert(key, Some(task_id)); + } else { + assert_eq!(diff, -1); + updates.entry(key).or_insert(None); + } + } + updates + .into_iter() + .map(move |(key, task_id)| (key, task_id, batch.time)) + }); + let active_requests = arrange_from_upsert::< + S, + Spine>>, + >(&request_updates, "AsyncTransformer: Current task") + .as_collection(|key, task_id| { + ( + Key::for_values(&[Value::Pointer(*key), Value::Pointer(*task_id)]), + *key, + ) + }); + + // Ignore completions for deleted or superseded rows. Deletion callbacks + // remain in `values` for the forgetting stream, but the input's pending + // stream already removes deleted rows from the output. + let completed = values + .inner + .flat_map( + |((key, _input_values, value, (seq_id, task_id)), time, diff)| { + if diff != 1 { + return None; + } + Some(( + ( + Key::for_values(&[Value::Pointer(key), Value::Pointer(task_id)]), + (value, seq_id), + ), + time, + diff, + )) + }, + ) + .as_collection(); + // Accepted results are retained by the upsert below. Forget each + // completion from the join so completed tasks do not accumulate there. + let forget_completed = completed + .inner + .map(|(data, time, diff)| (data, time.next_retraction_time(), -diff)) + .as_collection(); + let completed = completed.concat(&forget_completed); + let active: ArrangedByKey = + active_requests.arrange_named("AsyncTransformer: Active tasks"); + let completed: ArrangedByKey = + completed.arrange_named("AsyncTransformer: Completed tasks"); + active + .join_core( + &completed, + |_task: &Key, key: &Key, (value, seq_id): &(Value, i64)| { + std::iter::once((*key, Tuple::Zero, value.clone(), *seq_id)) + }, + ) + .filter_out_forgetting() } #[allow(clippy::too_many_arguments)] @@ -337,12 +439,16 @@ where .remove(&task_id) .expect("task_id has to be present"); - ((input_key, input_values, values, seq_id), time, diff) + ( + (input_key, input_values, values, (seq_id, task_id)), + time, + diff, + ) } }) .as_collection(); - run_output_connector( + let assigned_requests = run_output_connector( graph, table_handle, column_paths, @@ -352,6 +458,8 @@ where skip_errors, )?; + let live_results = keep_current_results(&assigned_requests, &values); + let table = graph .tables .get(table_handle) @@ -368,7 +476,7 @@ where (key, Tuple::Zero, Value::Pending, 0) }); - let output_values = values + let output_values = live_results .concat(&pending) .consolidate_for_output(false) .flat_map(|batch| { @@ -376,8 +484,8 @@ where for ((key, _input_values, values, seq_id), diff) in batch.data { match keep.entry(key) { Entry::Occupied(mut entry) => { - let (_, _, entry_seq_id) = entry.get(); - if seq_id > *entry_seq_id { + let (_, entry_diff, entry_seq_id) = entry.get(); + if diff > *entry_diff || (diff == *entry_diff && seq_id > *entry_seq_id) { entry.insert((values, diff, seq_id)); } } From cb8efac10d75c22e25099b1cc4e492d2f6843d87 Mon Sep 17 00:00:00 2001 From: Sergey Date: Mon, 30 Nov 2026 23:14:38 +0100 Subject: [PATCH 4/4] test: reuse license requirement fixture --- python/pathway/conftest.py | 7 ------- python/pathway/io/mysql/__init__.py | 2 +- python/pathway/tests/test_nested_lake_schema.py | 2 +- python/pathway/tests/test_nested_schema_docs.py | 2 +- 4 files changed, 3 insertions(+), 10 deletions(-) diff --git a/python/pathway/conftest.py b/python/pathway/conftest.py index 3a853c17f..c461b34a4 100644 --- a/python/pathway/conftest.py +++ b/python/pathway/conftest.py @@ -15,7 +15,6 @@ AIRBYTE_FAKER_CONNECTION_REL_PATH, SerializationTestHelper, make_port_fixture, - only_with_license_key, ) @@ -54,14 +53,8 @@ def local_pathway_config(environment_variables): @pytest.fixture -@only_with_license_key def requires_license() -> None: """Require a configured license key for a test or doctest.""" - - -@pytest.fixture -def skip_without_license() -> None: - """Skip a test or doctest when licensed features cannot be exercised.""" if not config.get_pathway_config().license_key: pytest.skip("requires a Pathway license key") diff --git a/python/pathway/io/mysql/__init__.py b/python/pathway/io/mysql/__init__.py index 90d3bb4d5..0f7bc9168 100644 --- a/python/pathway/io/mysql/__init__.py +++ b/python/pathway/io/mysql/__init__.py @@ -195,7 +195,7 @@ def read( ``{"price": 12.5, "content": "AQI="}``. Bytes inside the JSON value use base64, even when the database also supports native binary columns. - >>> getfixture("skip_without_license") # NODOCS + >>> getfixture("requires_license") # NODOCS >>> import pathway as pw >>> class Payload(pw.Schema): ... price: float diff --git a/python/pathway/tests/test_nested_lake_schema.py b/python/pathway/tests/test_nested_lake_schema.py index c53a2eae2..e4da98f0b 100644 --- a/python/pathway/tests/test_nested_lake_schema.py +++ b/python/pathway/tests/test_nested_lake_schema.py @@ -17,7 +17,7 @@ @pytest.fixture(params=[False, True], ids=["parquet", "arrow-backfill"]) -def lake_reader(request, tmp_path, skip_without_license): +def lake_reader(request, tmp_path, requires_license): def read(rows, arrow_type, schema): location = tmp_path / "lake" write_deltalake( diff --git a/python/pathway/tests/test_nested_schema_docs.py b/python/pathway/tests/test_nested_schema_docs.py index aa4a41494..f3d2b1506 100644 --- a/python/pathway/tests/test_nested_schema_docs.py +++ b/python/pathway/tests/test_nested_schema_docs.py @@ -48,7 +48,7 @@ def test_nested_schema_read_docstring_example( "postgres", "rabbitmq", }: - request.getfixturevalue("skip_without_license") + request.getfixturevalue("requires_license") reader = getattr(pw.io, connector).read # Python 3.13+ can strip the common indentation when compiling docstrings. doc = inspect.cleandoc(reader.__doc__) if clean_docstring else reader.__doc__