Repository navigation
[Core][2/n] report metrics to prometheus for lineage reconstruction - #67365
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
There was a problem hiding this comment.
Code Review
This pull request introduces two new high-cardinality counter metrics, task_submissions and object_recovery_attempts, to track task submissions and object recovery attempts within the core worker. It registers these metrics in the Python telemetry module to manage their cardinality. The review feedback correctly points out that because Prometheus appends a _total suffix to counter metrics, the high-cardinality metric list in Python must include this suffix to match and filter them properly. Updating this list also allows for simplifying the corresponding test assertions by removing fallback lookup logic.
Kunchd
left a comment
There was a problem hiding this comment.
The change looks good overall! But I left some comments on refining the task submission counter metric.
8136bce to
c50c507
Compare
1902c40 to
bba3352
Compare
) ## 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. **#66845 — [Data][1/n] Collect lineage reconstruction and stability metrics** ← this PR 2. #67365 — [Core][2/n] report metrics to prometheus for lineage reconstruction 3. #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: ```json { "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.) ```mermaid 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 ``` ### 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: ```bash 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](https://claude.com/claude-code) --------- Signed-off-by: Dhruvil Shah <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Collect the following stats for lineage reconstruction * ray_object_recovery_attempts_total * ray_task_submissions_total These metrics are reported to prometheus; they are later collected by the data usage collection actor for reporting per dataset based lineage reconstruction performed; Signed-off-by: Dhruvil Shah <[email protected]>
Replace ray_task_submissions{IsRetry} with ray_task_retry_submissions{Reason,Name},
recorded in TaskManager where the retry is decided. Reason is the failed
attempt's ErrorType name, or LINEAGE_RECONSTRUCTION for resubmits of finished
tasks. Recording before async_retry_task_callback_ also covers actor creation
retries. Drop Name at the low cardinality level, as for ray_tasks.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Dhruvil Shah <[email protected]>
bba3352 to
d49b2ec
Compare
Co-authored-by: Kunchen (David) Dai <[email protected]> Signed-off-by: Dhruvil Shah <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 1ddfb10. Configure here.
| "Total number of recovery attempts for lost objects owned by this worker. A lost " | ||
| "object can contribute one Pin attempt if recoverable via secondary copy. ", | ||
| "It can also contribute a reconstruct attempt if no copy could be found." | ||
| /*unit=*/"", |
There was a problem hiding this comment.
Misplaced comma splits metric description
Low Severity
A comma after the first description sentence turns the next string into the unit argument of ray::stats::Count. Adjacent-literal concatenation then joins that sentence with the intended empty unit, so object_recovery_attempts is registered with a truncated description and a prose unit.
Reviewed by Cursor Bugbot for commit 1ddfb10. Configure here.
There was a problem hiding this comment.
Not intended, thanks for catching it. The comma made the rest of the description the metric's unit. Fixed in 796bbce: the sentences are joined again so the description is whole and the unit stays empty.
| /*name=*/"object_recovery_attempts", | ||
| /*description=*/ | ||
| "Total number of recovery attempts for lost objects owned by this worker. A lost " | ||
| "object can contribute one Pin attempt if recoverable via secondary copy. ", |
There was a problem hiding this comment.
Nit: cursor comment, Is this comma here expected?
There was a problem hiding this comment.
Not intended, thanks for catching it. The comma made the rest of the description the metric's unit. Fixed in 796bbce: the sentences are joined again so the description is whole and the unit stays empty.
## 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]>


Summary
Add two Core worker Prometheus counters,
ray_task_retry_submissions_total{Reason,Name}andray_object_recovery_attempts_total{Type}. #66845 reads them to fill intask_retriesand, when Ray Data reconstruction is off,lineage_reconstruction.object_reconstruction_attemptsin Ray Data's per-execution usage entry.Stack
Before
Core exported no counter for task retries or for object recovery attempts. The Data queries in #66845 (
sum(ray_task_retry_submissions_total)andsum(ray_object_recovery_attempts_total{Type='Reconstruct'})) matched no series, so both fields always reported0.After
ray_task_retry_submissions_totalReason= the failed attempt'srpc::ErrorTypename (OUT_OF_MEMORY,WORKER_DIED,NODE_DIED,TASK_EXECUTION_EXCEPTION, ...)TaskManager::RetryTaskIfPossibleray_task_retry_submissions_totalReason="LINEAGE_RECONSTRUCTION"TaskManager::ResubmitTask,TaskManager::MarkGeneratorFailedAndResubmitray_object_recovery_attempts_totalType="Pin"ObjectRecoveryManager::PinExistingObjectCopyray_object_recovery_attempts_totalType="Reconstruct"ObjectRecoveryManager::ReconstructObjectray_task_retry_submissions_totalalso carriesName(the function name, as inray_tasks). It is recorded right beforeasync_retry_task_callback_, the only path intoCoreWorker'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
CoreWorkerProcessImpland passed by reference asMetricInterface&(intoTaskManagerandObjectRecoveryManager), like the existingtask_by_state/total_lineage_bytesmetrics. Tests swap inFakeCounter.Both are added to the high-cardinality metric list in
metric_cardinality.py, soWorkerIdis dropped at the defaultrecommendedlevel, andNameis also dropped for the retry counter atlow, as forray_tasks. The list holds OTLP instrument names (task_retry_submissions); Prometheus adds the_totalsuffix only when it exposes the counter.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 addedDuplicate check
gh pr list --repo ray-project/ray --state open --search ...forobject_recovery_attempts,task_retry_submissionsandtask retries metricreturns no other PR adding these counters. There's no linked issue.Testing
Locally on macOS:
task_manager_test:TestTaskOomAndNonOomKillReturnsLastErrorchecks oneOUT_OF_MEMORYand oneWORKER_DIEDretry, and none for the final failure that isn't retried.TestResubmitTaskchecks oneLINEAGE_RECONSTRUCTIONresubmit, and none for the calls that skip resubmission.object_recovery_manager_test:TestPinNewCopyrecords 2Pin/ 0Reconstructattempts, andTestReconstructionrecords 0Pin/ 1Reconstruct.test_metric_cardinality.pynow runs a task that fails once withretry_exceptions=True, so it can checktask_retry_submissionsat 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