Skip to content

[Feature][AI CLI] Correlate realtime queue pressure with downstream work - #12992

Merged
davidzollo merged 5 commits into
apache:devfrom
CryoThrust:feat/realtime-pressure-diagnosis-20261026
Nov 17, 2026
Merged

davidzollo merged 5 commits into
apache:devfrom
CryoThrust:feat/realtime-pressure-diagnosis-20261026

Conversation

@CryoThrust

@CryoThrust CryoThrust commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

This contribution to Apache SeaTunnel implements the read-only scope agreed in #12750. Closes #12750. #12688 brought both the job and checkpoint diagnosis paths into dev; #12631 was closed as superseded. This branch starts from current dev (4f5e32937) and contains only the realtime follow-up.

--diagnose can describe restart/checkpoint problems, but cannot yet connect a persistently full queue to work in its downstream vertex. This adds fixture-driven rules over the existing realtime edge/vertex endpoints, without an LLM or new dependency.

Does this PR introduce any user-facing change?

Yes, for RUNNING jobs on unreleased dev. Diagnosis makes two additional GET requests for realtime metrics. Job/checkpoint findings remain available if either optional request fails or observability is disabled.

  • Require the latest three consecutive completed buckets in the shared endpoint window, with matching bucket widths and target vertex. Missing/conflicting recent data cannot fall back to an older matched run.
  • Preserve each queue ID. Backpressure ≥ 0.5 and fill ≥ 0.8 in every bucket identify sustained pressure. Downstream sink/transform busyness is corroborating evidence, not proof of cause; source read time alone is never source attribution.
  • Report sink prepare/commit time separately, normalized by bucket duration and subtask count, including when sink write busyness is low.
  • Report disabled, missing or insufficient evidence as a coverage gap. No submit, stop, savepoint or provider construction is added.

Actual CLI output against loopback HTTP fixtures (synthetic timestamps, five-second buckets):

Job 852 (unnamed) — RUNNING
  [warning] Queue -3 into vertex 1 was persistently backpressured in the matched window. Downstream sink
writes were busy too; investigate this vertex as a bottleneck candidate. (queueId=-3 targetVertexId=1
buckets=3 window=0..15000ms bucketMs=5000 median bpRatio=0.80 queueFillRatio=0.90)

With observability disabled:

Job 852 (unnamed) — RUNNING
  [info] Realtime pressure checks unavailable: engine.observability.enabled is false.

English and Chinese CLI documentation includes the thresholds and evidence limits.

How was this patch tested?

cd seatunnel-cli
python -m pytest tests -q
ruff check .
black --check seatunnel_cli/diagnostics/realtime.py

Python 3.10 and 3.13 each pass 388 tests plus three subtests. Ruff and the new module's Black check pass. Tests cover sustained/transient pressure, stale/missing/conflicting buckets, partial windows, disabled metrics, shared targets, idle upstream, commit-only work and non-default bucket widths. Loopback HTTP tests exercise actual GET paths, terminal output, optional endpoint failure and execution without constructing a model provider.

Root-only Maven spotless:apply and verify -DskipTests also pass. This does not establish live-cluster behavior or a full Zeta reactor result; model-generation benchmarks are unaffected by this model-free branch.

Check list

  • Updated English and Chinese CLI documentation.
  • Added positive and negative tests to existing diagnosis/CLI test classes.
  • No new dependencies, binary packages, connector registration or incompatible configuration changes.

@DanielLeens DanielLeens 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 a lot for this follow-up, @CryoThrust. The evidence discipline here is really well thought out: latest-three-complete-buckets only, no fallback to stale runs, conflicting duplicates dropped, and "candidate to investigate" wording instead of claiming a root cause. Below is a full review of head 7884ea931f3d. I have read the diff and cross-checked the engine side by reading source; I did not run any build or test locally.

What Problem Does This PR Solve?

User pain point: seatunnel --diagnose can explain restart and checkpoint problems, but it cannot connect a persistently full, backpressured queue to work happening in the downstream vertex. An operator still has to read the raw /metrics/realtime endpoints by hand.

Fix approach: For RUNNING jobs only, the CLI issues two extra GETs (/metrics/realtime/jobs/<id>/edges and /vertices, windowMs=180000) and feeds them to a new pure function diagnose_realtime() in diagnostics/realtime.py. It emits realtime_queue_pressure, realtime_sink_commit_pressure and realtime_unavailable findings. No LLM, no provider construction, no new dependency, no engine change.

One-sentence summary: A model-free, read-only rule layer in the Python CLI that flags sustained queue backpressure and correlates it with downstream sink/transform busyness, reporting gaps explicitly.

1. Code Change Review

1.1 Core Logic Analysis

Changed files: seatunnel-cli/seatunnel_cli/cli.py (+14/-1), new seatunnel-cli/seatunnel_cli/diagnostics/realtime.py (+218), tests in test_diagnose_cli.py and test_diagnose_job.py, and README.md / README.zh-CN.md.

Runtime path (CLI only, no Zeta engine code touched):

seatunnel --diagnose <id>
 -> run_diagnose()  (cli.py)
    -> job-info + checkpoints (existing)
    -> if status == RUNNING: GET .../edges?windowMs=180000, GET .../vertices?windowMs=180000
       -> diagnose_realtime(edges, vertices)
          -> shared window = [max(fromMs), min(toMs)]; bucketMs must match
          -> _points(): keep aligned, complete (ts + width <= end) buckets; drop conflicting duplicates
          -> _recent_run(): require the latest 3 complete buckets, no stale fallback
          -> bp >= 0.5 AND fill >= 0.8 in all 3 -> queue_pressure (+ sink/transform busy >= 0.5 corroboration)
          -> (prepare+commit)/(bucket*subtasks) >= 0.5 in all 3 -> sink_commit_pressure

Before:

# two GETs only

After:

if status.upper() == "RUNNING":
    try:
        edges = rest.request_json(f"{metric_base}/edges?windowMs=180000", timeout=10)
        vertices = rest.request_json(f"{metric_base}/vertices?windowMs=180000", timeout=10)
    except Exception as e:
        edges, vertices = None, None
        logger.debug(...)
    findings = sort_findings(findings + diagnose_realtime(edges, vertices))

I verified the contract against the engine producer in RealtimeMetricsService.java (toEdgesResponse / toVerticesResponse / edgePoint / vertexPoint, roughly lines 548-700, and the empty/disabled responses around line 730):

  • Field names match: fromMs, toMs, bucketMs, edges[].queueId/targetVertexId/points[], vertices[].vertexId/points[], ts, bpRatio, queueFillRatio, sinkBusyRatio, transformBusyRatio, sinkPrepareCommitNs, sinkCommitNs, subtaskCount, and enabled:false on a disabled store.
  • Bucket starts are epoch-aligned ((nowMs / bucketMs) * bucketMs), so the ts % width alignment check is correct.
  • bpRatio is indeed not clamped to 1 in edgePoint while the vertex and fill ratios are clamped, which matches the author's deliberate _number vs _ratio split.
  • The normal path does reach the new code: any RUNNING job diagnosed against a cluster hits the new block. The status.upper() == "RUNNING" guard is right because the realtime store is not kept for finished jobs.

Correctness findings: none blocking. The "latest three complete buckets" logic, the end = min(toMs) shared clock (edges and vertices are fetched in two separate requests so their toMs differ slightly) and the per-queue incomplete_queues accounting all look correct. Failure of either optional request degrades to an info coverage-gap finding rather than dropping job/checkpoint evidence.

1.2 Compatibility Impact

Fully compatible. CLI-only, additive findings, no change to existing option names, defaults, REST contracts, serialization, checkpoint or engine behavior. The only user-visible delta is two more GET requests for RUNNING jobs, and the feature is gated by engine.observability.enabled (the disabled case is reported as a coverage gap, not an error). On older clusters without these endpoints, RestError is swallowed into the same gap notice.

1.3 Performance / Side-Effect

  • Two extra sequential GETs with a 10s timeout each. Worst case adds up to ~20s to a --diagnose call on a hung metrics endpoint; typical cost is milliseconds. Response size is bounded by MAX_RESPONSE_BYTES in rest.py, and the window is fixed at 3 minutes, so memory is bounded. See Issue 2.
  • Pure in-memory evaluation, O(queues x buckets). No impact on the Zeta engine, no extra load beyond two read-only endpoint calls against a store the engine already maintains.

1.4 Error Handling and Logging

Overall good: malformed values (bool, NaN/inf, negative, out-of-range ratios, non-int ids) are treated as missing rather than as evidence, and the broad except Exception is justified by the "optional evidence" contract and still surfaces an info finding to the user.

Issue 1

  • Location: seatunnel-cli/seatunnel_cli/cli.py realtime block (except Exception as e: ... logger.debug(...)) and diagnose_realtime() messages.
  • Problem description: When the metrics request fails (timeout, connection reset, 404, 5xx, bad JSON), the user only sees "an endpoint or its metric window is missing". The actual reason is logged at debug level only.
  • Potential risk: Low. Operators cannot tell "endpoint not available on this cluster version" from "transient timeout" without re-running with debug logging.
  • Best improvement: Carry a short, credential-redacted reason (for example the HTTP status or exception class) into the realtime_unavailable detail, similar to how the checkpoint path reports its own gap.
  • Severity: Low
  • Raised by another reviewer: No

Issue 2

  • Location: cli.py, the two sequential rest.request_json(..., timeout=10) calls.
  • Problem description: If the first request times out, the second is still attempted, doubling the wait.
  • Potential risk: Low. A diagnose command against a wedged cluster feels slow, exactly when the user is already stressed.
  • Best improvement: Skip the vertices request when the edges request failed, or share one deadline.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality

2.1 Coding Standards

Issue 3

  • Location: seatunnel-cli/seatunnel_cli/diagnostics/realtime.py, helpers _window, _points, _recent_run, diagnose_realtime and the threshold constants BACKPRESSURE_RATIO, QUEUE_FILL_RATIO, BUSY_RATIO.
  • Problem description: _points and _recent_run have docstrings, but the constants (and why 0.5 / 0.8 / 0.5) and the _window / _integer / _number / _ratio semantics (what is treated as invalid, and why bpRatio uses _number instead of _ratio) are only explained by an inline comment deep in diagnose_realtime. The README documents the thresholds, but the code does not.
  • Potential risk: Low. Future maintainers may "fix" the bpRatio > 1 handling or retune thresholds without understanding the engine contract.
  • Best improvement: Add a one-line comment per threshold constant (mark them as initial, evidence-limited heuristics) and a short docstring on _window / _ratio linking the unclamped bpRatio fact to RealtimeMetricsService.edgePoint.
  • Severity: Low
  • Raised by another reviewer: No

Other standards: the ASF license header is present, the code follows the existing Finding / sort_findings conventions, imports are clean. PR title prefix [Feature][AI CLI] is not in the module list from the contributing guide, but that is a nit and there is no established module name for the CLI yet.

2.2 Test Coverage and Test Stability

Coverage is thorough and tests are fixture driven: sustained vs transient pressure, partial/current bucket, stale and conflicting data, mixed bucket widths, disabled store, shared target vertex with several queues, idle upstream, commit-only pressure, non-default bucket widths, and loopback HTTP tests that assert GET-only behavior and that no model provider is constructed. The tests mutate existing test classes rather than adding new ones, which matches the repository guidance. Tests use synthetic toMs values, so there is no wall-clock dependency.

Rating: Stable (no sleeps, no real clock, loopback server fixtures only; I see no flakiness path in seatunnel-cli/tests/test_diagnose_cli.py or test_diagnose_job.py).

CI note: at review time GitHub reports no check runs for this head, and the merge state is BLOCKED. The author's description lists a local run of 388 tests, which I have not reproduced. Please make sure the PR workflow runs for this head before merge.

2.3 Documentation

README.md and README.zh-CN.md are both updated with the thresholds, the evidence limits, and the sample output. English and Chinese content are in parity. The new behavior is documented, including the disabled-observability message. No docs/en / docs/zh engine change is needed because the engine is untouched.

3. Architectural Soundness

3.1 Precise fix / Temporary workaround / Long-term solution

This is a long-term solution within its stated scope: it consumes the engine's already published realtime API and does not invent a second metric path. It is deliberately limited to what the endpoints can prove.

3.2 Maintainability

Good. Detection is isolated in one new pure module and the cli.py change is small. The strict-evidence design is easy to unit test. Minor: diagnose_realtime is long (~110 lines); consider splitting queue-pressure and sink-commit-pressure into two functions later.

3.3 Extensibility

Good. New rules can be added as additional passes over vertex_points / edge series using the same helpers. The thresholds are module constants, so tuning is local.

3.4 Historical-version compatibility

No impact on released engines or jobs: the code path is CLI-only and unreleased dev. Clusters lacking the realtime endpoints or with observability off degrade to an info finding while job and checkpoint diagnosis is unchanged.

4. Issue Summary

Number Issue Location Severity
1 Failure reason for optional metrics only at debug level cli.py realtime block Low
2 Second request still sent after the first one times out (up to ~20s) cli.py realtime block Low
3 Threshold constants and ratio helpers lack explanatory comments diagnostics/realtime.py Low

5. Merge Recommendation

Conclusion: Ready to merge

Blockers: none (no non-CI blockers).

Non-blocking fixes: Issues 1-3 above are all Low and can be addressed in this PR or a follow-up.

Gate: CI had not reported any check runs for head 7884ea931f3d when I reviewed it, so I am not approving yet. Once the PR workflow runs green on this head, this is good to go. I have not claimed any runtime validation of my own: the review is source-based and cross-checked against RealtimeMetricsService.java.

Overall assessment: Careful, conservative, well tested, and honest about what the evidence can and cannot prove. Nice work.

Alternatives considered: Putting the correlation in the engine REST layer would couple a heuristic to the server and make threshold tuning a release-bound change; keeping it in the CLI as done here is the lower-risk choice.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the contribution. The CI fact cited in my previous conclusion has changed; this follow-up updates that gate on the unchanged reviewed head, without issuing another full source review.

Gate snapshot (2026-10-28T15:52:57+00:00), head 7884ea931f3dbf4d6c8464c1aacf69e49431397f: Build is ACTION_REQUIRED.

The exact blocking stage is Build workflow-run detection: the check says no fork Build was found for this SHA. This is not an executed test failure and does not by itself prove that fork Actions is disabled. Open the fork Actions tab, enable workflows if needed, then manually run the existing Build workflow for this PR branch. If a matching run already exists, link it for a maintainer to reconcile the aggregate. No empty commit or speculative dependency change is requested.

Upstream check: current dev retains the fork-run adoption workflow and its scheduled/manual status-refresh path. A base sync alone cannot enable fork Actions or supply a missing exact-head workflow run, so I am not prescribing sync as the fix for this activation gate.

My previous source conclusion remains clear for the reviewed scope. CI is not being passed by inference, and this follow-up is not an effective approval.

Comparison recorded in this scan: base dev, diverged, ahead 5 / behind 37, no merge conflict. Branch drift is metadata here and is not an additional sync request.

@CryoThrust

CryoThrust commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

The fork's Actions page was still showing a repository-level disabled-workflows notice even though the API reported Actions enabled. I re-enabled workflows there and synced the fork's default branch to pick up the manual Build trigger.

A Build run completed successfully for this PR's unchanged head, 7884ea931: https://github.com/CryoThrust/seatunnel/actions/runs/43150883647 . The upstream PR now reports all five checks successful, including Build and the Python 3.10/3.13 tests. No empty commit or PR history rewrite was needed.

@DanielLeens DanielLeens 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 @CryoThrust for enabling the fork workflows and linking the exact-head run. That is the missing evidence my previous reply asked for; no empty commit is needed.

The CI fact cited previously has changed. On unchanged head 7884ea931f3dbf4d6c8464c1aacf69e49431397f, fork Build 43150883647 completed successfully, and the Apache Build check is now green. My earlier pending/missing-workflow guidance is obsolete. My previous conclusion had no remaining source-side blocker. CI was previously the only remaining blocker from my side; CI is now passing, so the conclusion is being changed to approve.

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed: None from my existing source review or current CI. Effective maintainer review remains required; other reviewers retain control of their own outstanding review records.
  2. Recommended fixes — non-blocking: Earlier optional suggestions remain optional. No unrelated source change is requested to chase CI.

Comparison with dev: diverged, ahead 5 / behind 133; no conflict was reported in the comparison snapshot. Behind is metadata, not a sync request. This is a discussion and CI-gate update on an already-reviewed head, not another full source review. No local build or job was executed. Daniel has READ permission: this technical approval does not substitute for a write-capable maintainer's approval/dismissal or merge action.

@davidzollo davidzollo 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.

+1
LGTM

Thanks for your contribution!

Please join our Apache SeaTunnel contributors channel on Slack for technical discussions and collaboration: https://s.apache.org/seatunnel-slack

@davidzollo
davidzollo added this pull request to the merge queue Nov 17, 2026
Merged via the queue into apache:dev with commit 5d8937d Nov 17, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature][AI CLI] Correlate realtime pressure with downstream execution evidence

3 participants