Skip to content

[Data][1/n] Collect lineage reconstruction and stability metrics - #66845

Merged
sampan-s-nayak merged 7 commits into
ray-project:masterfrom
NightWing1998:metrics
Oct 29, 2026
Merged

sampan-s-nayak merged 7 commits into
ray-project:masterfrom
NightWing1998:metrics

Conversation

@NightWing1998

@NightWing1998 NightWing1998 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Report per-execution lineage reconstruction and stability metrics in Ray Data's usage payload: whether reconstruction ran, object-lost task failures, reconstruction attempts, task retries, and object store / task memory usage. The goal is to measure whether lineage reconstruction improves pipeline stability.

Stack

  1. [Data][1/n] Collect lineage reconstruction and stability metrics #66845 — [Data][1/n] Collect lineage reconstruction and stability metrics ← this PR
  2. [Core][2/n] report metrics to prometheus for lineage reconstruction #67365 — [Core][2/n] report metrics to prometheus for lineage reconstruction
  3. [Data][3/n] update progress bar on lineage reconstruction #67366 — [Data][3/n] update progress bar on lineage recovery

Before

Each execution's usage entry recorded only bytes_spilled, oom_kills, unexpected_worker_kills and node_deaths. Nothing showed whether lineage reconstruction was on, how often objects were lost or rebuilt, or how much memory the pipeline used. A task whose lost output was being reconstructed was torn down through the failure path (mark_aborted(lost_error)), so it counted as a failed task even when reconstruction recovered its output.

After

Each execution's usage entry now records:

  • env.context.enable_ray_data_reconstruction: whether this execution actually ran with Ray Data lineage reconstruction. It is read from the executor, so it is false when the DAG doesn't support reconstruction even if the DataContext requested it. Only allowlisted executor settings (_EXECUTION_SETTINGS) are recorded, so no user-defined values reach the usage data.
  • performance.task_retries, performance.object_store_memory_bytes, performance.task_max_uss_bytes
  • performance.lineage_reconstruction.object_reconstruction_attempts and performance.lineage_reconstruction.num_object_lost_task_failures

lineage_reconstruction.object_reconstruction_attempts counts lost objects that lineage reconstruction tried to rebuild, whichever side ran it. env.context.enable_ray_data_reconstruction says which side that was:

  • true: Ray Data reconstruction ran, and Ray Core lineage reconstruction is off for the job. The count is LineageTracker.num_object_reconstruction_attempts, incremented once per lost object before _reconstruct_lost_object.
  • false: the count is Ray Core's ray_object_recovery_attempts_total{Type='Reconstruct'}.

Abort mechanism: reconstructed tasks are aborted, not failed

When _reconstruct_lost_object tears down a task whose output was lost, it used to call mark_aborted(lost_error), which went through the normal failure path (on_task_finished with an exception). For usage collection that is wrong in three ways:

  1. Failure counts. The torn-down task counted in num_tasks_failed and, since its error is an ObjectLostError, in num_object_lost_task_failures. These counts went up exactly when reconstruction succeeded, so they couldn't tell recovered losses from real failures.
  2. Double counting. The task also counted in num_tasks_finished and its inputs in num_task_inputs_processed / bytes_task_inputs_processed, and the replacement task counts again when it finishes.
  3. Why a separate flag. Passing no exception would make the torn-down task look like a successful finish: it would be counted as finished and reported to the LineageTracker as a completion. Passing the error alone makes it a failure. An explicit flag is the only way to release the task's reservations without counting it either way, while keeping the lost-object error.

The change:

  • _reconstruct_lost_object calls DataOpTask.mark_aborted(lost_error, aborted_for_reconstruction=True). TaskDoneCallbackType gains an aborted argument, which is True only for these tasks, and exception still carries the lost-object error for observability and error handling. Only lineage-tracked tasks may be aborted for reconstruction; this is asserted.
  • MapOperator._task_done_callback routes aborted=True to the new OpRuntimeMetrics.on_task_aborted, which only releases what on_task_submitted reserved, and skips the LineageTracker completion. on_task_finished and on_task_aborted share _release_task_inputs, so both paths release the same reservations.
  • Real failures still go through on_task_finished, including mark_aborted(recon_error) when reconstruction itself fails. on_task_finished now counts ObjectLostError failures in num_tasks_failed_object_lost.
  • The other TaskDoneCallbackType implementations (hash shuffle, shuffle reduce, GPU shuffle) take the new argument and ignore it, since they never run lineage-tracked tasks.

A successful Prometheus query that matches no series now reads as 0 instead of None: Ray creates a counter's series only on its first event. None is still returned for real failures (Prometheus unreachable, non-200, malformed body). Fields whose value is None are left out of the payload.

Example entry:

{
    "executions": [
        {
            ...
            "env": {
                ...
                "context": {
                    "enable_ray_data_reconstruction": false
                }
            },
            ...
            "performance": {
                "bytes_spilled": 0,
                "oom_kills": 0,
                "unexpected_worker_kills": 0,
                "node_deaths": 0,
                "task_retries": 0,
                "object_store_memory_bytes": {
                    "num_samples": 555,
                    "min": 0,
                    "max": 84560,
                    "mean": 43173.10810810814,
                    "sum": 23961075.00000002,
                    "variance": 581758211.8474971
                },
                "lineage_reconstruction": {
                    "object_reconstruction_attempts": 0,
                    "num_object_lost_task_failures": 0
                }
            },
            ...
        }
    ]
}

(task_max_uss_bytes has the same shape as object_store_memory_bytes and is omitted here because USS is only reported on Linux.)

flowchart TD
    subgraph Before
        subgraph BE[Subsystem: execution]
            B1["_reconstruct_lost_object"] -->|"mark_aborted(lost_error)"| B2["on_task_finished<br/>(counted as failed)"]
        end
        subgraph BO[Subsystem: observability / usage]
            B3["_compute_cluster_deltas<br/>(4 Prometheus counters)"] --> B4[PipelinePerf]
        end
    end
    subgraph After
        subgraph AE[Subsystem: execution]
            A1["_reconstruct_lost_object"] -->|"mark_aborted(lost_error,<br/>aborted_for_reconstruction=True)"| A2["on_task_aborted<br/>(not counted)"]
            A3["task error on driver"] --> A4["on_task_finished<br/>counts ObjectLostError failures"]
            A5["hash shuffle finalize task"] --> A6["_reduce_metrics"]
        end
        subgraph AO[Subsystem: observability / usage]
            A7["on_execution_step<br/>object store sample"] --> A10[PipelinePerf]
            A4 --> A8["_collect_op_metrics<br/>USS + object-lost count"]
            A6 --> A8
            A8 --> A11["PipelinePerf.lineage_reconstruction"]
            A9["_compute_cluster_deltas<br/>+ reconstruction attempts, task retries"] --> A10
            A9 --> A11
            A14["LineageTracker<br/>num_object_reconstruction_attempts"] -->|"Ray Data reconstruction on"| A11
            A12["executor.ray_data_reconstruction_enabled"] --> A13["EnvInfo.context"]
        end
    end
    classDef removed fill:#ffcdd2,stroke:#c62828,color:#000
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    classDef changed fill:#fff9c4,stroke:#f9a825,color:#000
    class B2 removed
    class A2,A4,A6,A7,A8,A11,A12,A13,A14 added
    class A1,A9,A10 changed
Loading

Collected by the Data executor (in-process, no Prometheus)

Field Source When it's collected
object_store_memory_bytes (MemoryStats: num_samples, min, max, mean, sum, variance) executor._resource_manager.get_global_usage().object_store_memory Sampled on every scheduling-loop step (UsageCallback.on_execution_step)
task_max_uss_bytes (MemoryStats) max_uss_bytes (DistributionTracker) merged across all operators, including hash shuffle finalize tasks (_reduce_metrics); workers report it from MemoryProfiler At execution end. Linux only, so always omitted on macOS
lineage_reconstruction.object_reconstruction_attempts (when enable_ray_data_reconstruction is true) LineageTracker.num_object_reconstruction_attempts: one per lost object Ray Data tries to rebuild, counted whether or not the attempt succeeds, like Ray Core's Type=Reconstruct At execution end
lineage_reconstruction.num_object_lost_task_failures Sum of num_tasks_failed_object_lost across operators, including hash shuffle finalize tasks: failed tasks whose error is an ObjectLostError or a RayTaskError caused by one At execution end. Tasks aborted for reconstruction aren't counted. A loss that user code catches and re-raises as its own exception isn't detected

Scraped from Prometheus (delta between execution start and end, scoped by SessionName)

Field PromQL Exists in OSS core?
bytes_spilled sum(ray_spill_manager_objects_bytes{State='Spilled'}) Yes, but it's a gauge (bytes spilled right now), so restored objects can make the delta undercount (floored at 0)
node_deaths sum(ray_node_failure_total) Yes (GCS)
oom_kills sum(ray_memory_manager_worker_eviction_total) Yes (raylet)
unexpected_worker_kills sum(ray_node_manager_unexpected_worker_failure_total) Yes (raylet)
task_retries sum(ray_task_retry_submissions_total) No, added in #67365
lineage_reconstruction.object_reconstruction_attempts (when enable_ray_data_reconstruction is false) sum(ray_object_recovery_attempts_total{Type='Reconstruct'}) No, added in #67365

Until #67365 lands, these two counters have no series, so they report 0.

Subsystems

Observability (usage collection) carries the new data. Execution carries the behavioral change: reconstructed tasks are aborted instead of failed, and TaskDoneCallbackType gains aborted. Shuffle / aggregation has mechanical ripple edits: the aborted argument in the shuffle operators' done callbacks.

Duplicate check

gh pr list --repo ray-project/ray --state open --search ... for "lineage reconstruction usage", "usage collection metrics data", object_reconstruction_attempts and num_object_lost returns no other PR doing this work. There's no linked issue.

Testing

Each file was run on its own, locally on macOS:

pytest python/ray/data/tests/test_usage.py                   # 34 passed
pytest python/ray/data/tests/test_op_runtime_metrics.py      # 19 passed
pytest python/ray/data/tests/test_lineage_reconstruction.py  # 24 passed
pytest python/ray/data/tests/test_streaming_executor.py      # 54 passed
pre-commit run --files <changed files>                       # passed

AI assistance (Claude Code) was used for parts of this change.

🤖 Generated with Claude Code

@NightWing1998
NightWing1998 marked this pull request as ready for review October 15, 2026 05:58
@NightWing1998
NightWing1998 requested a review from a team as a code owner October 15, 2026 05:58
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Oct 15, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 200e0b6. Configure here.

@NightWing1998 NightWing1998 changed the title [DRAFT][Data] Collect lineage reconstruction flag as open telemetry metric [Data] Collect lineage reconstruction flag as open telemetry metric Oct 16, 2026

@ayushk7102 ayushk7102 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we refactor to have a separate dataclass for LineageReconstruction usage stats? Also, I have a few questions about the implementation

NightWing1998 and others added 3 commits October 23, 2026 15:09
Record whether each execution ran with Ray Data lineage reconstruction.
The value comes from the executor
(StreamingExecutor.ray_data_reconstruction_enabled), so it reflects what
actually ran: it is off when the DAG doesn't support reconstruction,
even if the DataContext requested it.

The flag is recorded under env.context through _CONTEXT_WHITELIST, an
explicit allowlist of execution settings. No user-defined values
(paths, names, env vars) reach the usage data.

Signed-off-by: Dhruvil Shah <[email protected]>
Add per-execution performance fields to the usage payload:

- lineage_reconstruction.object_reconstruction_attempts: delta of
  ray_object_recovery_attempts_total{Type="Reconstruct"}.
- lineage_reconstruction.num_object_lost_task_failures: failed tasks
  whose error is an ObjectLostError, or a RayTaskError caused by one.
  Counted on the driver in OpRuntimeMetrics, hash shuffle finalize
  tasks included.
- task_retries: delta of ray_task_submissions_total{IsRetry="true"}.
- object_store_memory_bytes: Ray Data's object store usage, sampled on
  every scheduling step.
- task_max_uss_bytes: peak USS of finished tasks across operators.

A task whose lost output is being reconstructed is now aborted rather
than failed. mark_aborted(None) passes aborted=True to the task done
callback, and OpRuntimeMetrics.on_task_aborted releases the task's
reservations without counting it as finished or failed. Reconstruction
therefore no longer inflates failure counts.

The two Prometheus counters are added on the Core side in <CORE PR>.

Signed-off-by: Dhruvil Shah <[email protected]>
Ray creates a counter's series only on its first event, so a
successful query that matches no series now returns 0 instead of None.
A counter that first appears mid-execution still yields a delta instead
of being dropped. None is still returned for real failures:
Prometheus unreachable, a non-200 response, or a malformed body.

Fields whose value is None are now left out of the usage payload.

Signed-off-by: Dhruvil Shah <[email protected]>
@NightWing1998 NightWing1998 changed the title [Data] Collect lineage reconstruction flag as open telemetry metric [Data] Collect lineage reconstruction and stability metrics in usage telemetry Oct 23, 2026
@NightWing1998 NightWing1998 changed the title [Data] Collect lineage reconstruction and stability metrics in usage telemetry [Data] Collect lineage reconstruction and stability metrics Oct 23, 2026
@NightWing1998 NightWing1998 changed the title [Data] Collect lineage reconstruction and stability metrics [Data][1/n] Collect lineage reconstruction and stability metrics Oct 24, 2026

@ayushk7102 ayushk7102 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we update the description with the changes in the abort mechanism and why they are needed for the correctness of usage collection?

NightWing1998 and others added 2 commits October 27, 2026 21:54
- Query ray_task_retry_submissions_total for task retries.
- Rename the context allowlist to _EXECUTION_SETTINGS and type
  collect_context's result as ContextInfo; only a missing executor
  attribute is recorded as None.
- Rename _collecting to _collection_enabled.
- Document why only lineage-tracked tasks can be aborted.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
When Ray Data lineage reconstruction runs (Ray Core lineage reconstruction
is then off for the job), report lineage_reconstruction.object_reconstruction_attempts
from the executor's LineageTracker: one attempt per lost object Ray Data tries
to rebuild, mirroring ray_object_recovery_attempts_total{Type=Reconstruct}.
Otherwise keep reading the Ray Core counter.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>

@ayushk7102 ayushk7102 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks, LGTM!

mark_aborted now always takes the error and an explicit
aborted_for_reconstruction flag, instead of None meaning "aborted for
reconstruction". The intent is explicit at the call site and the
lost-object error stays available to the done callback.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01SFgt6e8asGBUjNHyirrBnj
Signed-off-by: Dhruvil Shah <[email protected]>
@NightWing1998 NightWing1998 added the go add ONLY when ready to merge, run all tests label Oct 29, 2026
Assert _executor and the lineage tracker are set before reading them in
build_usage_info, so pyrefly can narrow the Optionals. Check the
reconstruction flag on two executors in the test so the second assert
isn't flagged as always false.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01SFgt6e8asGBUjNHyirrBnj
Signed-off-by: Dhruvil Shah <[email protected]>
@sampan-s-nayak
sampan-s-nayak merged commit f2bbaeb into ray-project:master Oct 29, 2026
6 checks passed
iamjustinhsu pushed a commit that referenced this pull request Oct 29, 2026
…67365)

## Summary

Add two Core worker Prometheus counters,
`ray_task_retry_submissions_total{Reason,Name}` and
`ray_object_recovery_attempts_total{Type}`. #66845 reads them to fill in
`task_retries` and, when Ray Data reconstruction is off,
`lineage_reconstruction.object_reconstruction_attempts` in Ray Data's
per-execution usage entry.

## Stack

1. #66845 — [Data][1/n] Collect lineage reconstruction and stability
metrics
2. **#67365 — [Core][2/n] report metrics to prometheus for lineage
reconstruction** ← this PR
3. #67366 — [Data][3/n] update progress bar on lineage recovery

## Before

Core exported no counter for task retries or for object recovery
attempts. The Data queries in #66845
(`sum(ray_task_retry_submissions_total)` and
`sum(ray_object_recovery_attempts_total{Type='Reconstruct'})`) matched
no series, so both fields always reported `0`.

## After

| Metric | Tag values | Recorded in | When |
|---|---|---|---|
| `ray_task_retry_submissions_total` | `Reason` = the failed attempt's
`rpc::ErrorType` name (`OUT_OF_MEMORY`, `WORKER_DIED`, `NODE_DIED`,
`TASK_EXECUTION_EXCEPTION`, ...) | `TaskManager::RetryTaskIfPossible` |
The owner schedules a retry of a failed attempt |
| `ray_task_retry_submissions_total` | `Reason="LINEAGE_RECONSTRUCTION"`
| `TaskManager::ResubmitTask`,
`TaskManager::MarkGeneratorFailedAndResubmit` | The owner re-runs a
finished task to recover a lost object |
| `ray_object_recovery_attempts_total` | `Type="Pin"` |
`ObjectRecoveryManager::PinExistingObjectCopy` | Each attempt to promote
a secondary copy of a lost object to primary |
| `ray_object_recovery_attempts_total` | `Type="Reconstruct"` |
`ObjectRecoveryManager::ReconstructObject` | Each attempt to resubmit
the task that created a lost object |

`ray_task_retry_submissions_total` also carries `Name` (the function
name, as in `ray_tasks`). It is recorded right before
`async_retry_task_callback_`, the only path into `CoreWorker`'s resubmit
queue, so it covers normal, actor and actor creation tasks. First
submissions aren't counted.

Both counters are created once per worker in `CoreWorkerProcessImpl` and
passed by reference as `MetricInterface&` (into `TaskManager` and
`ObjectRecoveryManager`), like the existing `task_by_state` /
`total_lineage_bytes` metrics. Tests swap in `FakeCounter`.

Both are added to the high-cardinality metric list in
`metric_cardinality.py`, so `WorkerId` is dropped at the default
`recommended` level, and `Name` is also dropped for the retry counter at
`low`, as for `ray_tasks`. The list holds OTLP instrument names
(`task_retry_submissions`); Prometheus adds the `_total` suffix only
when it exposes the counter.

```mermaid
flowchart TD
    subgraph Core[Subsystem: core worker]
        P[CoreWorkerProcessImpl] -->|"owns ray::stats::Count"| C1[task_retry_submissions_counter_]
        P -->|"owns ray::stats::Count"| C2[object_recovery_attempts_counter_]
        subgraph TM[TaskManager]
            T1["RetryTaskIfPossible"] -->|"Reason=ErrorType name"| R[RecordTaskRetrySubmission]
            T2["ResubmitTask /<br/>MarkGeneratorFailedAndResubmit"] -->|"Reason=LINEAGE_RECONSTRUCTION"| R
            R --> CB["async_retry_task_callback_<br/>(CoreWorker resubmit queue)"]
        end
        R --> C1
        R1["ObjectRecoveryManager::PinExistingObjectCopy"] -->|"Type=Pin"| C2
        R2["ObjectRecoveryManager::ReconstructObject"] -->|"Type=Reconstruct"| C2
        R2 -->|"resubmits creating task"| T2
    end
    C1 --> PR[(Prometheus)]
    C2 --> PR
    PR -->|"delta per execution"| D["Ray Data usage (#66845)"]
    classDef added fill:#c8e6c9,stroke:#2e7d32,color:#000
    class C1,C2,R added
```

## Duplicate check

`gh pr list --repo ray-project/ray --state open --search ...` for
`object_recovery_attempts`, `task_retry_submissions` and `task retries
metric` returns no other PR adding these counters. There's no linked
issue.

## Testing

Locally on macOS:

```bash
bazel test --dynamic_mode=off \
  //src/ray/core_worker/tests:task_manager_test \
  //src/ray/core_worker/tests:object_recovery_manager_test \
  //src/ray/core_worker/tests:core_worker_test           # 3 passed
pre-commit run --files <changed files>                   # passed
```

* `task_manager_test`: `TestTaskOomAndNonOomKillReturnsLastError` checks
one `OUT_OF_MEMORY` and one `WORKER_DIED` retry, and none for the final
failure that isn't retried. `TestResubmitTask` checks one
`LINEAGE_RECONSTRUCTION` resubmit, and none for the calls that skip
resubmission.
* `object_recovery_manager_test`: `TestPinNewCopy` records 2 `Pin` / 0
`Reconstruct` attempts, and `TestReconstruction` records 0 `Pin` / 1
`Reconstruct`.
* `test_metric_cardinality.py` now runs a task that fails once with
`retry_exceptions=True`, so it can check `task_retry_submissions` at
each cardinality level. **Not run locally yet**: it needs a Ray build
that includes these C++ changes.

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]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Kunchen (David) Dai <[email protected]>
NightWing1998 added a commit to NightWing1998/ray that referenced this pull request Oct 30, 2026
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]>
pseudo-rnd-thoughts pushed a commit to pseudo-rnd-thoughts/ray that referenced this pull request Oct 30, 2026
goutamvenkat-anyscale pushed a commit that referenced this pull request Oct 30, 2026
… 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]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 12, 2026
…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]>
sampan-s-nayak pushed a commit that referenced this pull request Nov 19, 2026
## 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants