Repository navigation
[Data] (Fault tolerance #5/n) Optimization: Batch tasks submitted for Data lineage reconstruction - #66990
Conversation
…age reconstruction Signed-off-by: Ayush Kumar <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request updates Ray Data's lineage reconstruction to allow a single seed task re-execution to serve multiple reconstruction plans simultaneously. It transitions from tracking a single reconstruction_plan_id to a set of reconstruction_plan_ids across operators and tasks, and introduces a mechanism for plans to join already queued seed re-executions. The feedback highlights a potential NameError in map_operator.py due to sorted_reconstruction_plan_ids being conditionally defined but referenced in nested callbacks, as well as an incomplete comment that needs to be finished.
…hing Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Signed-off-by: Ayush Kumar <[email protected]>
Kunchd
left a comment
There was a problem hiding this comment.
Thanks for the PR! My main comment here is, from my understanding, we only avoid redundant work on the seed task. Any other child task that's shared between multiple plans are still executed multiple times. Have we considered working on a followup for this?
| output_index=output_index, | ||
| ) | ||
| ] = output | ||
| elif status is ObjectReuseStatus.OBJECT_NEW: |
There was a problem hiding this comment.
Is it possible for the output to be new for some of the plans but not others? If not, should we be asserting that here?
There was a problem hiding this comment.
Good question. An object can NOT be new for some plans, but reused for others. This is because you can only get NEW from the target task of the plan (the leaf task), and it literally means that the output indices that were reached in the first attempt of this task had not reached this far (and therefore, this object index is NEW). The object indices only goes up and is incremented when the block is actually delivered to the operator queue.
An output is REUSED only when a child consumed it in the earlier run. A child can only consume a delivered output (something that was added to the operator queue), so that index is always below the count of object indices. NEW needs the index to be at or past the count, while REUSED needs the object index to be below the count.
However, a block can (and often will be) NEW for some plans and PRUNED for others. This is because a block is PRUNED if the plan uses this task, but none of its (child, output_index) entries name the index of the block.
| self._queued_seed_reexecutions: Dict[ | ||
| LineageTaskId, Set[ReconstructionPlanId] | ||
| ] = {} |
There was a problem hiding this comment.
Instead of tracking which plans are batched under a seed, would it be cleaner to just make the stamp support tracking multiple plans? Then we can more easily extend to batching downstream reconstruction task to further reduce redundant work in the future.
There was a problem hiding this comment.
Yep. We now make the stamp track multiple plans.
There was a problem hiding this comment.
One implementation detail however is that we still need to keep track of some state - to track all tasks that are batched after the bundle has been added to the operator queue, because at this point, we can't mutate the bundle's metadata (and the plan set needs to be a frozen set)
Then on actual task submission (when the bundle is popped from the queue) we take the bundle for a downstream reconstruction task and replace it's frozen set of plans with a new set of plans that include the existing plans (from the upstream batching) and the new plans that were batched while this bundle was queued.
| still queued, so the second plan joins it. The single re-run must withhold each | ||
| re-produced output under the plan whose child needs it, and release each child | ||
| once under its own plan. | ||
| """ |
There was a problem hiding this comment.
How is this case different from test_second_loss_joins_the_queued_seed_re_execution?
There was a problem hiding this comment.
test_second_loss_joins_the_queued_seed_re_execution was checking that two losses trces back to one seed, and that the seed task is reinjected once.
test_shared_seed_re_execution_serves_every_joined_plan was the second half of the test which dealt with the outputs, checking that the single run served both plans, and released each child once with its own stamp.
I've combined these into a single test to cover the entire case
| for task in consumer._data_tasks.values() | ||
| ) == [(child_task_id, frozenset({plan_id})) for plan_id in plan_ids] | ||
|
|
||
|
|
There was a problem hiding this comment.
Could we add a test case that ensures we don't join a seed attempt that's already been submitted?
There was a problem hiding this comment.
Added a case for this test_loss_after_the_seed_re_execution_is_submitted_re_injects_the_seed
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
…truction Signed-off-by: Ayush Kumar <[email protected]>
Kunchd
left a comment
There was a problem hiding this comment.
Thanks for addressing all of the previous comments. I left one minor nit and a potential followup item to consider, but we should be good to go.
| self, lineage_task_id: str, reconstruction_plan_id: str, task_index: int | ||
| self, | ||
| lineage_task_id: str, | ||
| reconstruction_plan_ids: FrozenSet[ReconstructionPlanId], |
There was a problem hiding this comment.
nit: could we document the arguments of this function?
| @@ -754,10 +751,10 @@ def _task_done_callback( | |||
| # Hand any child whose whole input set this completion completes | |||
| # downstream before reporting the completion itself. | |||
| if sorted_reconstruction_plan_ids: | |||
| self._release_reconstruction_blocks_to_child( | |||
| lineage_task_id, reconstruction_plan_ids, task_index | |||
| ) | |||
There was a problem hiding this comment.
Might not need to be addressed in this PR if it's too much work. If we only release reconstruction task upon one of the parent task completion, aren't we releasing too slowly? Couldn't we release the child reconstruction task as soon as the final output block it needs is produced?
There was a problem hiding this comment.
That's a good point, thanks for raising! Modified the approach to keep track of the last output index needed (or the last block's index, which needs to be withheld for children tasks). From this we can know when we have reached the final output block that needs to be reused by children, and immediately we can release reconstruction children.
This can help prevent long waits for the reconstruction children to be scheduled if say: only output index 0 is reused, 1...99 are pruned, but we need to wait from output 0 to 99 to be processed, and the task to be completed in order to release the reconstruction blocks downstream.
| def _consumer_of(self, child_task_id: LineageTaskId) -> "LineageReconstructionMixin": | ||
| """The downstream operator that owns ``child_task_id``.""" | ||
| for op in self.output_dependencies: | ||
| if isinstance(op, LineageReconstructionMixin) and op.owns_data_task( | ||
| child_task_id | ||
| ): | ||
| return op |
There was a problem hiding this comment.
Why is this only returning the 1st consumer?
💬 via pr-lens
There was a problem hiding this comment.
Only a single task can have a given lineage task ID. We check all and early return when we find it.
Signed-off-by: Ayush Kumar <[email protected]>
…x that is wittheld is produced, not on task completion Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
| for op in self.output_dependencies: | ||
| if isinstance(op, LineageReconstructionMixin) and op.owns_data_task( | ||
| child_task_id | ||
| ): |
There was a problem hiding this comment.
why do you need to sort the plan ids?
💬 via pr-lens
There was a problem hiding this comment.
For deterministic reruns., if we fix the order of execution of the tasks. This is not strictly necessary and we can remove it if it becomes a bottleneck due to many parallel reconstructions (i.e. under heavy chaos)
|
Chatted with @goutamvenkat-anyscale and we talked about a potential follow-up , basically we want to prevent the O(n^2) query everytime to build the Can we store extra state on the lineage tracker which has this information built out (for each child, dependencies that are completed) in the form of sets |
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
ray-project#66845 added the aborted argument to the data task done callback, and ray-project#66990 merged after it with three test calls that pass only the first three arguments, which raise TypeError and fail the pyrefly check. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01SFgt6dBsnVtrSvVBoxQPsf Signed-off-by: Dhruvil Shah <[email protected]>
… task_done_callback (#67578) ## Why `linux://python/ray/data:test_lineage_reconstruction` is flaky on master: it failed at least once on 28% of its last 18 postmerge runs, including 4 failures in the last 24h (e.g. https://buildkite.com/ray-project/postmerge/builds/20608#01a18a22-3992-4d59-b8da-523d5dcf497a). ## What `python/ray/data/tests/test_lineage_reconstruction.py`: pass `aborted=False` as the fourth positional argument in the three direct `task._task_done_callback(...)` calls. #66845 added a required `aborted` parameter to `MapOperator`'s task-done callback, and #66990 added these tests with the old 3-argument call. As a result, 5 tests fail with `TypeError: ... _task_done_callback() missing 1 required positional argument: 'aborted'` in every config on master since #66990 merged. ## Testing Lint only (ruff, black). The test was not run locally; CI on this PR runs it. --- _Generated by [Claude Code](https://claude.ai/code/session_0113UwSedinWzVUR14PP62Nf)_ Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…age reconstruction (#67519) ## Description Adds a manual release test, `image_embedding_from_uris_fake_gpu_lineage_reconstruction_chaos`, that exercises Ray Data lineage reconstruction under node loss and checks that the output is still exactly right. The driver starts with `JobConfig(_disable_job_level_lineage_reconstruction=True)`, so lost objects are rebuilt by Ray Data rather than Ray Core. A `RayletKiller` then kills worker raylets mid-run. It replaces `EC2InstanceTerminatorWithGracePeriod`, which drains a node before stopping it, so no objects are lost and reconstruction never runs. Changes to `image_embedding_from_uris/main.py`: - `--lineage-reconstruction` starts the driver with the job config above. With `--chaos`, the run counts calls to `LineageTracker.register_task_failed` that resubmit seed tasks. It fails if that count is 0, so a run where chaos never lost a needed object can't pass silently. The count is written to `result.json` as `lineage_reconstructions`. - `--fake-gpu` swaps in `FakeEmbedPatches`, which sleeps for the measured T4 inference time, so the test runs on 20 m5.2xlarge nodes that advertise a logical `GPU: 1` (`fake_gpu_small_cluster_compute.yaml`) instead of 100 g4dn nodes. Lineage reconstruction doesn't depend on real GPUs. - `--verify-output` runs the new `verify_output.py` against the sink after the write. - `create_metadata` adds a dense `row_serial` taken from the source order, so a re-executed task reproduces the same values. - `RAY_DATA_WRITE_PATH` optionally overrides the sink, which makes manual reruns of the verifier easier. `verify_output.py` reads the sink with pyarrow, not Ray Data, so a Ray Data bug can't hide itself. `(row_serial, patch_x, patch_y)` is a primary key and the full expected key set is known up front (69,000 images × 36 patches = 2,484,000 rows). The script checks: - completeness (dropped rows) - uniqueness (rows from over-reconstruction) - that every image produced its full patch set - that `row_serial` agrees with the metadata next to it, which catches a reconstructed block carrying the wrong rows It can also be run on its own, and `--sample-embeddings N` spot-checks embedding values. All new flags default to off, so the existing `image_embedding_from_uris_fixed_size` test is unchanged. The one shared change is the chaos killer used by `--chaos`, which only this new test passes. ## Related issues Related to the Ray Data lineage reconstruction series (#66136, #66990). Not a duplicate: I searched open PRs for "lineage reconstruction release test" and found no other PR adding a release test for Data lineage reconstruction. #66845 adds metrics and #66990 adds batching; neither touches release tests. ## Additional information **Testing** - `black --check` on `main.py` and `verify_output.py`: passes. - End-to-end run on a 20-node fake-GPU Anyscale workspace: <TODO: result, lineage_reconstructions count, verify_output summary> **AI assistance**: I wrote this with help from Claude Code, then reviewed every changed line myself. --------- Signed-off-by: Ayush Kumar <[email protected]>
## Summary Show Ray Data lineage reconstruction activity in each operator's progress bar as `Reconstruction: X queued, Y running, Z finished`, so users can see that a lost object is being rebuilt rather than the pipeline stalling. ## Stack 1. #66845 — [Data][1/n] Collect lineage reconstruction and stability metrics (merged) 2. #67365 — [Core][2/n] report metrics to prometheus for lineage reconstruction (merged) 3. **#67366 — [Data][3/n] update progress bar on lineage reconstruction** ← this PR ## Before When a task's output was lost and Ray Data reconstructed it, the only signs were a `logger.warning` and `[lineage-reconstruction]` info logs. The operator progress line looked like normal progress, so a reconstruction looked like the pipeline had stalled or was re-doing work for no reason. ## After With Ray Data lineage reconstruction enabled, a `MapOperator`'s progress line ends with: ``` Tasks: 1; Actors: 0; Queued blocks: 0 (0.0B); Resources: ...; Reconstruction: 0 queued, 1 running, 2 finished ``` * **queued**: reconstruction tasks of this operator whose input is queued but not yet submitted, both re-injected seed inputs and child inputs released by a parent. This is `len(self._batched_plans)`, which holds one entry per queued reconstruction task. A loss that is batched into an already-queued task doesn't add one. * **running**: active data tasks with non-empty `reconstruction_plan_ids`. A task serving several batched plans counts once. * **finished**: reconstruction tasks that completed successfully, once per task however many plans it served. Aborted or failed attempts aren't counted. The count stays on the line after reconstruction finishes. The status only appears once the operator has had reconstruction activity. When reconstruction is disabled (no `LineageTracker`), the line is unchanged. It shows in the tqdm, rich and logging progress output, which all build their line from `format_op_state_summary`. ```mermaid flowchart TD subgraph Before subgraph BE[Subsystem: execution] B1["_reconstruct_lost_object"] -->|"re-inject stamped seed input"| B2["MapOperator._submit_data_task"] B2 --> B3["_task_done_callback"] end subgraph BO[Subsystem: observability / progress] B4["format_op_state_summary"] --> B5["tqdm / rich / logging progress"] end end subgraph After subgraph AE[Subsystem: execution] A1["_reconstruct_lost_object"] -->|"re-inject stamped seed input<br/>or batch into the queued task"| A2["MapOperator._submit_data_task"] A2 --> A3["_task_done_callback<br/>success + plan ids: finished += 1"] A6["LineageReconstructionMixin<br/>_batched_plans (queued) / finished counter"] A7["MapOperator.lineage_reconstruction_progress_str<br/>running = _data_tasks with reconstruction_plan_ids"] end subgraph AO[Subsystem: observability / progress] A4["format_op_state_summary<br/>+ '; Reconstruction: ...'"] --> A5["tqdm / rich / logging progress"] end A1 -.-> A6 A3 -.-> A6 A6 --> A7 --> A4 end classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000 classDef changed fill:#fff9c4,stroke:#f9a825,color:#000 class A6,A7 added class A3,A4 changed ``` `PhysicalOperator.lineage_reconstruction_progress_str()` returns `""` by default. `MapOperator` overrides it, since it is the only operator that runs reconstruction tasks. ## Subsystems Observability (progress) carries the user-visible change. Execution has a small bookkeeping edit: the finished counter in `LineageReconstructionMixin`, incremented in `MapOperator._task_done_callback`. Tests: three calls to the data task done callback in `test_lineage_reconstruction.py` now pass the `aborted` argument. #66845 added that argument and #66990 merged after it with calls that pass only three, which raise `TypeError` and fail the pyrefly check. ## Duplicate check `gh pr list --repo ray-project/ray --state open --search ...` for "lineage reconstruction progress bar" and "reconstruction progress_str" returns only this PR. There's no linked issue. ## Testing Locally on macOS: ```bash pytest python/ray/data/tests/test_lineage_reconstruction.py # 32 passed pytest python/ray/data/tests/unit/test_lineage_reconstruction_progress.py # 2 passed (post-rename) pytest python/ray/data/tests/test_usage.py # 34 passed bash ci/lint/pyrefly-check.sh # no findings in changed files pre-commit run --files <changed files> # passed ``` The clustered line in `test_lineage_reconstruction.py` is exercised by CI; the local checkout needs a post-rebase C++ rebuild before it can run there. The cluster-free tests and all lint hooks were re-run locally after the rename commit. New tests: * `test_reconstruction_status_counts_queued_running_and_finished` (unit): queued counts the entries in `_batched_plans`, only tasks with `reconstruction_plan_ids` count as running (once each, even when serving two plans), and the status is empty without a tracker. * `test_reconstruction_status_records_the_re_run_task`: after a real injected seed loss, the seed operator reports `Reconstruction: 0 queued, 0 running, 1 finished`. * `test_summary_str_lineage_reconstruction` (unit): `format_op_state_summary` adds the status only when reconstruction is enabled and has activity, and keeps the finished count afterwards. AI assistance (Claude Code) was used for parts of this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Dhruvil Shah <[email protected]> Signed-off-by: Dhruvil Shah <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
…ng executor integration tests to prevent flakiness (#68049) ## Description This PR rewrites all of the integration tests for lineage reconstruction as well as some unit tests, to fix flakiness in the test suite. ### Why `test_lineage_reconstruction` was flaky in CI. This is because several tests simulated a lost block with a `lose_output` fixture that monkeypatched `DataOpTask.on_data_ready` to raise `ObjectLostError` on the Nth time the executor polled a given task. The problem is that the number of polls it takes to drain a task is non-deterministic. It depends on whether metadata is fetched on a background thread or inline, and on how fast tasks are submitted and finish. the task drained before the Nth poll, so the loss never fired and an assertion based on the number of reconstructions failed. ### Integration test changes Rather than relying on executor poll timing/task completion time, we now encode a failure into the data itself (i.e. a particular row will tell the UDF to mock a lost block). A `map_batches` UDF raises `ObjectLostError` when it sees a specific row, and the executor handles that exactly like a block lost with its node. The end-to-end tests then check that the loss actually happened, and every row comes back exactly once. They cover linear, fan-in, fan-out, multi-operator, actor pool and write pipelines, plus a block that's lost a second time while it's being reconstructed. ### Unit test changes I reworked all of the old lineage reconstruction unit tests that are specific to the integration with the streaming executor. The purely unit tests that don't need a Ray cluster moved to `tests/unit/test_lineage_reconstruction_executor.py`. No production code changes. ## Related issues Related to #66220 and #66990. ## Additional information I checked open PRs and nothing else rewrites these tests. #67366, #67885 and #68042 add tests to the same file, so whichever of us lands second will need to rebase. Testing: I ran the unit tests 30 times and the integration tests 6 times (3 with the threaded metadata fetcher, 3 with the inline one). Everything passed every time. --------- Signed-off-by: Ayush Kumar <[email protected]>
Description
When several tracked tasks lose their output, each failure opens its own reconstruction plan. If those plans trace back to the same task, today each one re-injects the seed separately, so the read runs once per plan. So does every downstream task that the plan shared. That is a lot of redundant work during reconstruction.
Let's say there are two different downstream objects that are lost independently, which result in two separate reconstruction plans A and B. Let's also say that both plans A and B trace back to the same seed task (say T). With the changes from this PR, we should now only re-submit the seed task T once for both plans. This "batching" can be done by noticing that the traced seed task for a plan is already queued for submission (but not submitted yet), and simply joining on to the same seed task. By updating the lineage tracking metadata, we can use the same seed to emit block outputs required for multiple different reconstruction plans at the same time.
The
LineageTrackerAPI is unchanged. Batching is purely an optimization. If a plan can't be batched, behavior is exactly what it was before, with the task re-run for that plan. We can only batch reconstruction plans with a queued task because if it is submitted, it's likely that it is too late, and the required output block for the second plan has already been dropped due to beingOBJECT_PRUNEDat the time.Limitations:
Related issues
Optimization on top of the Ray Data integration with lineage tracker API first started in #66220
Additional information
Tests
New or updated tests in
test_lineage_reconstruction.py:test_losses_before_the_seed_is_submitted_share_one_reconstruction_task: two real losses through_reconstruct_lost_objectre-inject the seed once, and the one run serves both plans, holding and releasing outputs correctly for each.test_joined_plans_sharing_a_child_release_it_once: a child both plans need is released once, stamped with both plans, and runs once.test_shared_child_is_batched_until_it_is_submitted: a plan joins a queued child, or re-runs it if the child was already submitted.test_seed_targeted_by_one_plan_and_reused_by_another: one run serves a plan it is the target of and a plan it is an intermediate of.test_loss_after_the_seed_reconstruction_task_is_submitted_re_injects_the_seed: a new plan due to a object loss after another plan's submission can no longer join it, and rather is re-submitted as a new plan