Skip to content

[Feature][seatunnel-cli] Diagnose a gradual slowdown from checkpoint history - #12688

Merged
davidzollo merged 2 commits into
apache:devfrom
SEZ9:cli-diagnose-checkpoints
Oct 14, 2026
Merged

davidzollo merged 2 commits into
apache:devfrom
SEZ9:cli-diagnose-checkpoints

Conversation

@SEZ9

@SEZ9 SEZ9 commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Closes #12685

Benchmark

Per our convention of leading with benchmark numbers: this change cannot move
the L1 static smoke preset, and I would rather say so than report a
meaningless delta. --diagnose returns before any provider is constructed, and
this PR adds one module plus one best-effort GET behind that same flag — no
prompt, no tool spec, no planner path is touched, so there is nothing for a
generation benchmark to measure. The run-to-run spread on identical code is
around ±5 tasks, which would swamp any effect even if one existed.

What this rests on instead is 27 new tests (271 total, up from 245 on the
parent branch), including mutation checks on the three assumptions below.

Why

The rules added in #12631 all compare against zero or a fixed threshold. That
answers "did it break" and "is it stuck", but not the question people actually
ask about a long-running CDC job — it was fine at first and now it lags. Such a
job is RUNNING, both row counters keep moving and restoreCount is 0, so
every rule we have stays silent. Running --diagnose against exactly that
shape today produces one line:

Job 852 mysql-cdc-to-doris — RUNNING
  [info] Running for 72h00m. (state=RUNNING)

Which restates what the user already knew.

What

GET /jobs/checkpoints/<jobId> is the one place the engine publishes a
series rather than a current value, so the job can be compared against its
own recent past. Six rules read it:

rule severity fires when
checkpoint_duration_growing warning recent checkpoints take ≥2× what earlier ones took
checkpoint_state_growing info recent state is ≥2× earlier state — usually the cause of the above
checkpoint_bound warning a checkpoint takes ≥80% of the gap between triggers
checkpoint_never_completed warning checkpoints are triggered but completed == 0
checkpoint_failing warning failed > 0, with the engine's own failureReason
checkpoint_stalled error one has been in progress > 120s, naming unacknowledged subtasks

Two of these answer different questions on purpose. A trend needs a baseline,
so it only sees degradation still inside the retained window. A ratio
(checkpoint_bound) needs no baseline at all, which is what makes it work for
the job that degraded yesterday and has been slow ever since — the common case
by the time someone asks for help.

The same scenario now gets an actionable answer:

Job 852 mysql-cdc-to-doris — RUNNING
  [warning] Pipeline 1 has 19 failed checkpoints. ... Last failure: checkpoint expired before completing (failed=19)
  [warning] Pipeline 1 checkpoints are getting slower: recently 48.0s against 4.0s earlier in the retained
            history. ... (median durationMillis 4000 -> 48000 over 16 checkpoints)
  [warning] Pipeline 1 now spends almost all its time checkpointing: a checkpoint takes 48.0s and one is
            triggered every 1m00s. Raise checkpoint.interval, or find why the snapshot is slow ...
            (recent median duration 48000ms vs interval 60000ms)
  [info] Running for 72h00m. (state=RUNNING)
  [info] Pipeline 1 checkpoint state is growing: recently 120.0MiB against 12.0MiB earlier. ...

Still read-only, still no LLM call, so it works with no API key and no provider
configured. The checkpoint read is best-effort on purpose: an engine without
the endpoint, or a cluster with the checkpoint monitor off, still gets the rest
of the diagnosis rather than a failure.

Three wire-format details the arithmetic depends on

Each of these fails silently — it yields a confident finding that is simply
backwards — so each has a dedicated regression test:

  1. history is newest-first. PipelineCheckpointOverview.addHistory uses
    history.addFirst(...) and CheckpointMonitorService.getHistory sorts by
    triggerTimestamp descending. Read in array order, every trend conclusion
    inverts. Pinned from both directions: a history that is getting faster
    must not be reported as slower.
  2. Failed checkpoints omit durationMillis entirely (it is a Long, and
    null fields are not serialized). Counted as zero they would halve the recent
    median and hide a real slowdown.
  3. Their stateSize is a primitive long, so it arrives as a plausible
    0 rather than being absent. Counted in, growing state looks like shrinking
    state.

All three are handled by filtering to status == "COMPLETED" before any
duration or state arithmetic — but intervals are computed from every entry,
because a checkpoint that failed was still triggered on schedule.

Honest limits

  • maxHistorySize is 32 per pipeline (SeaTunnelServer.java:202), so at a 10s
    interval the trend sees roughly five minutes, not three days. This is why
    checkpoint_bound exists.
  • Where the time goes (sink vs source) needs /metrics/realtime, which is a
    follow-up: engine.observability.enabled defaults to false, so that rule
    has a prerequisite this one does not, and it deserves its own PR.
  • The CDC snapshot→incremental transition is not exposed over REST at all
    (AssignerStatus appears nowhere in seatunnel-engine/), so it can only
    ever be a hint, never a rule. Not attempted here.

Also in this PR

Printing findings with markup=False. This fixes a real display bug in
#12631: "error" is a style name in the CLI theme, so rich was consuming the
[error] severity prefix as a style tag. Severity reached the user by colour
alone — invisible in a pipe, in CI, or under NO_COLOR. It also stops an
engine failure message containing brackets from corrupting the output, which is
newly reachable here because failureReason is passed through verbatim.

_as_int in jobs.py is renamed to as_int so a sibling module need not
import a private name, and sort_findings is extracted so findings from
several rule sets are ordered as one list — sorting each set separately would
put an info line from one above an error from another.

Stack

This is third in a stack and the diff includes its parents:

Review only the last commit, [Feature][seatunnel-cli] Diagnose a gradual slowdown from checkpoint history. I will rebase as the parents land.

Tests

271 pass (245 on the parent branch). ruff check . — the exact command
cli.yml runs — passes. Mutation-verified that the ordering assumption is
caught by 5 tests, the markup=False fix by 3, and the "unknown completed
count is not zero" guard by 1.

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

Hi @SEZ9, thanks for this one. The observation that every rule in #12631 compares against zero or a fixed threshold, and that "it was fine and now it lags" is the question people actually ask, is exactly right, and /jobs/checkpoints/<id> is the right place to look. I reviewed the part that is new in this PR (the third commit of the stack: diagnostics/checkpoints.py, the extra GET in run_diagnose, sort_findings, tests and README) at head 24179b2, and checked it against the engine source and REST docs. This is static analysis only; I did not run the PR locally.

What problem does this PR solve

  • Pain point: a long-running CDC job that slowly degrades stays RUNNING with moving counters and restoreCount 0, so --diagnose from #12631 prints only "Running for 72h".
  • Approach: add a best-effort second GET of /jobs/checkpoints/<id> and six rules over the checkpoint series (duration trend, state growth, checkpoint-bound ratio, never completed, failing, stalled in-progress), plus markup=False when printing findings.
  • In one sentence: the trend and ratio rules are well designed and correctly handle the wire format, but two count-based rules treat cumulative counters as current problems, and some Rich markup problems remain.

1. Code change review

Core logic. Before: one GET to /job-info. After: run_diagnose() also reads the checkpoint overview, merges both rule sets and sorts them as one list (sort_findings).

Runtime path

run_diagnose(job_id)
  -> GET /job-info/<id>            -> diagnose_job()
  -> GET /jobs/checkpoints/<id>    (best effort: any exception -> checkpoints = None)
        -> diagnose_checkpoints(): in-progress age, counts, duration trend, interval ratio, state trend
  -> sort_findings(job + checkpoint findings) -> console.print(..., markup=False) -> exit 1 only for FAILED

Verified against source: the response shape (counts, latestFailed, inProgress, history[].checkpoint) matches docs/en/engines/zeta/rest-api-v2.md; PipelineCheckpointOverview.addHistory uses addFirst, so history is newest first and the code's "recent half is the front of the list" is correct; failed entries have no durationMillis, which is why filtering to COMPLETED before arithmetic is necessary. The markup=False fix for finding lines is correct and I agree with it.

Compatibility: fully compatible (additive; an older engine without the endpoint just yields no checkpoint findings). The diff contains #12629 and #12631 because the PR is stacked.

Performance and side effects: one more GET with a 10s timeout; read-only.

Error handling and logging: malformed input yields fewer findings, which is the right default; see issue 4 for the silent skip.

Issues (new in this PR)

  1. (Medium) checkpoint_failing fires forever on a cumulative counter. Location: diagnostics/checkpoints.py _counts_findings (if failed:). counts.failed is a lifetime total. A job with one expired checkpoint weeks ago and thousands of completed ones since gets a warning saying offsets "stop advancing on every failure ... making no durable progress". Fix: compare latestFailed.triggerTimestamp with latestCompleted.triggerTimestamp (warn only when the latest failure is newer than the latest completion), or use the share of failed entries in the retained history, and include completed in the evidence text.
  2. (Medium) checkpoint_never_completed has no age gate. Location: same function (if triggered and completed == 0). Right after a job starts, triggered=1, completed=0, inProgress=1 is normal, yet the output says nothing has been committed and a restart replays from the beginning. Fix: require at least two triggers, or an in-progress/oldest trigger older than the stalled threshold, before saying this.
  3. (Medium) Markup is still interpreted in the non-finding lines. Location: cli.py run_diagnose: the header (Job [bold]..[/bold] {name}, where the job name is user chosen, for example [prod] sync) and the 404 / HTTP error / transport error lines ({e.body}, {e}). test_other_http_errors_show_the_engine_body only asserts the uppercase API-02, so it passes while ErrorDescription:[master is down] is swallowed. Use markup=False or escape these too.
  4. (Low) Silent skip can produce false reassurance. Location: run_diagnose, except Exception: checkpoints = None. If the checkpoint read times out or the monitor is off, the output can end with "Nothing to report: no rule matched this job's state." Please print one info line such as "Checkpoint history unavailable" (and logger.debug the exception) so users know that part of the analysis did not run.
  5. (Low) checkpoint_stalled compares the engine's triggerTimestamp with the client's local clock. The overview carries updatedAt; using it as "now" avoids skew.

Carried over from #12631 (the same code is in this diff, so they apply here until fixed in the parent): Rich markup in finding text and the missing label assertion, the cumulative restoreCount >= 2 crash-loop claim, the missing age gate on no_rows_read, the likely wrong default base port 5801 for /job-info (Jetty serves v2 on 8080), clock source, job-id validation and the DOING_SAVEPOINT wording. Please fix them once in #12631 and rebase this PR.

Merge state (blocker): the PR is DIRTY against dev (conflicts in cli.py, README.md, README.zh-CN.md) and depends on #12629 and #12631. Please rebase after the parents land.

2. Code quality

  • Standards: license headers, docstrings that explain why, thresholds with stated reasons (DURATION_FLOOR_MS, STATE_FLOOR_BYTES), shared sort_findings / as_int instead of importing private names. Good.
  • Tests: test_diagnose_checkpoints.py plus extended CLI tests, driven by an injected clock and a loopback server. Stability rating: Stable (no sleeps, ephemeral ports). The mutation checks you describe for the ordering assumption are a nice touch. Missing cases: a long-lived job with a single old failure (issue 1), a fresh job with one in-progress checkpoint (issue 2), and bracketed text in the header or HTTP-error body (issue 3).
  • Docs: README (en and zh) updated and consistent. The limits section in the PR description (32-entry window, no source vs sink split) is honest and helpful.

3. Architecture

Using the checkpoint series as the one place the engine publishes history is the right design, and keeping the checkpoint read best-effort is right too. The remaining gap is the same principle as in #12631: a rule should only say something a snapshot can support. Count-based rules need a recency or age condition; the trend and ratio rules already satisfy that.

4. Issue summary

# Severity Location Summary Blocking
1 Medium checkpoints.py _counts_findings checkpoint_failing fires on lifetime failed > 0 Yes
2 Medium checkpoints.py _counts_findings checkpoint_never_completed fires on a fresh job Yes
3 Medium cli.py run_diagnose Header and error lines still parsed as Rich markup Yes
4 Low cli.py run_diagnose Failed checkpoint read is silent, may print "Nothing to report" No
5 Low checkpoints.py _in_progress_findings Local clock vs engine timestamp No
- (inherited) #12631 items See carry-over list above Yes, via #12631
- Blocker PR branch vs dev Merge conflicts, stacked Yes

5. Merge recommendation

Not recommended for merge yet; the design is good and the fixes are small.

  • Blockers: issues 1 to 3, the inherited #12631 items, and the rebase.
  • Non-blocking: issues 4 and 5.
  • CI diagnosis: the apache-side Build check is a pointer. The real run in the fork for this head (Build run 37727068218) is green: Python 3.10, 3.13 and Lint passed; Java jobs were skipped because only seatunnel-cli changed. As with #12631, the open problems are not covered by the current tests.

Thanks again for the careful wire-format notes.

@SEZ9
SEZ9 force-pushed the cli-diagnose-checkpoints branch from 24179b2 to bcb55b4 Compare October 9, 2026 05:20
@SEZ9

SEZ9 commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @DanielLeens — all five items plus the rebase are addressed in bcb55b4ab, and the inherited #12631 items are fixed in the parent (now at d426a0b87), which this branch is rebased onto.

Your framing was right and it generalised further than the two rules you named: both blocking findings here are the same mistake as issues 2 and 3 in #12631 — a counter that accumulates over the job's lifetime, read as a statement about the present. counts is the worst offender because every value in it is cumulative.

1. checkpoint_failing on a lifetime counter (Medium, blocking) — fixed

The rule now asks "did the latest attempt fail", not "has anything ever failed", using the comparison you suggested:

  • latestFailed.triggerTimestamp newer than latestCompleted.triggerTimestamp → warning, now worded "and its latest checkpoint failed rather than completed"
  • a failure on record with nothing ever completed → warning (the latest failure is the only outcome there is)
  • the latest completion is newer → info checkpoint_failed_before: "has N failed checkpoints since it was submitted, but the most recent checkpoint completed, so it is committing progress now"
  • neither timestamp usable → info with the count and the engine's reason, and an explicit "Whether the latest one failed is not visible in this response"

completed is in the evidence string now, as you asked: failed=4 completed=36.

That last branch is a change from your suggestion worth flagging: an empty latestFailed object is a shape the engine really sends, and the existing test_a_failed_count_still_reports_when_the_reason_is_unusable pins that the measured count must not be discarded just because the explanation is missing. So the count still surfaces — as a note, with no claim about the present.

Tests: test_old_failures_under_a_newer_completion_are_not_a_warning (the 5000-completion pipeline carrying one expired checkpoint from 20 days ago — your exact scenario), test_a_failure_newer_than_the_last_completion_is_a_warning, test_failures_with_no_completion_on_record_are_a_warning.

2. checkpoint_never_completed on a fresh job (Medium, blocking) — fixed

It now needs one of the two gates you proposed: triggered >= MIN_TRIGGERS_NEVER_COMPLETED (2), or an in-progress checkpoint that has been in flight longer than STALLED_CHECKPOINT_SECONDS. triggered=1, completed=0, inProgress=1 three seconds in — the reading every healthy job has in its first interval — is now silent.

When the age gate is what fired, the evidence says so: triggered=1 completed=0 oldest in progress for 2m10s.

Tests: test_a_job_in_its_first_checkpoint_interval_is_not_reported_as_never_completing, test_a_first_checkpoint_that_is_already_overdue_is_reported, test_a_second_trigger_with_nothing_completed_is_reported_without_timestamps.

3. Markup in the non-finding lines (Medium, blocking) — fixed in the parent

Moved to #12631 as you asked, so this PR no longer carries that fix alone. There, rich.markup.escape() covers the header, the 404 line, the HTTP-error body and the transport-error line, and the test that asserted only the uppercase API-02 now asserts ErrorDescription:[master is down]. Details are in my reply on #12631, including the MarkupError reproduction for a bracketed path.

4. The silent skip (Low) — fixed

A failed checkpoint read now prints one line and logs the exception at debug:

  Checkpoint history unavailable, so the slowdown checks did not run
  (the cluster may predate the endpoint, or its monitor service is off).

You were right that the dangerous case is the combination: no job-level finding and no checkpoint read, where the output used to end at "Nothing to report" and read as "the slowdown checks ran and found nothing". test_a_healthy_job_with_no_checkpoint_data_does_not_look_fully_checked pins exactly that pair, and test_a_missing_checkpoint_endpoint_does_not_break_the_diagnosis now also asserts the notice.

5. Local clock vs engine timestamps (Low) — fixed

updatedAt is now the clock when now_ms is not injected, falling back to the local clock when the overview does not carry it. test_the_overview_updated_at_is_preferred_over_the_local_clock passes no now_ms at all, so the rule has to find its clock in the response.

For symmetry, the job rules in the parent now use diagnostics.generatedAt the same way.

Inherited items and the rebase

All the #12631 carry-overs are fixed in the parent, including the default base URL — I verified from JettyService, RestConstant and the packaged config/seatunnel.yaml that port 5801 cannot serve these paths, and the default is now 8080. That verification is static, from source and docs; I did not run a packaged distribution, so the empirical confirmation you asked for is still open. Full detail, including a scope note about changing a pre-existing default, is in my #12631 reply.

#12629 has merged. The conflict was the single cli.py import hunk; the two READMEs auto-merged rather than conflicting.

Verification

  • 312 tests pass locally, ruff check . clean with the ruff==0.16.7 that cli.yml pins.
  • CI green on this head: Build, Lint, Test with Python 3.10, Test with Python 3.13.
  • Wire-format and engine behaviour claims are read from source; nothing was run against a live cluster.

One housekeeping note, same as on the parent: because #12629 was squash-merged under a new SHA, this branch's merge base predates it and GitHub still replays rest.py and tests/test_rest.py into the diff. The content is byte-identical to dev, so it merges cleanly — I can rebase to drop it if a smaller diff would help the re-review. This PR will still carry #12631's commit until that one lands, as the description says.

Ready for another look.

@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 for the very detailed reply and for turning the earlier items around so quickly, @SEZ9. I re-reviewed the whole PR at the latest head bcb55b4a (static analysis against the engine source, I did not run the PR). I confirmed that the old-failure gate, the first-interval gate, the fixed markup=False / escape() handling, the "checkpoint history unavailable" notice on a failed read, and the rebase are all in the code.

First, an apology: one of the five items I raised last time was wrong, and that is on me. In my previous review I suggested using the checkpoint overview's updatedAt as "now" to avoid clock skew. I had not checked how the engine sets that field, and it does not work that way (Issue 1 below). Sorry for sending you in that direction, and thanks for your patience.

What problem does this PR solve?

  • Pain point: a long-running CDC job that slowly degrades stays RUNNING with moving counters and restoreCount 0, so --diagnose only printed "Running for 72h".
  • Approach: a best-effort second GET of /jobs/checkpoints/<id> and six rules over the checkpoint series (duration trend, state growth, checkpoint-bound ratio, never completed, failing, stalled), plus markup=False for finding lines.
  • One sentence: let --diagnose compare a job with its own recent checkpoint history, so "it was fine and now it lags" gets an actionable answer.

1. Code change review

1.1 Core logic

Runtime path (re-verified):

seatunnel --diagnose <id> -> run_diagnose()                                    cli.py (run_diagnose)
  -> GET /job-info/<id>            -> diagnose_job()            (diagnostics/jobs.py)
  -> GET /jobs/checkpoints/<id>    best effort: exception -> notice, checkpoints = None
       -> diagnose_checkpoints(overview): in-progress age, counts, duration trend, interval ratio, state trend
  -> sort_findings(job + checkpoint findings) -> print with markup=False + redact_credentials
  -> exit 1 only if jobStatus == FAILED

I re-checked the wire-format assumptions against the engine: PipelineCheckpointOverview.addHistory uses addFirst (newest first, so "recent half = front of the list" is right), failed entries have no durationMillis, and the scheduling assumption behind checkpoint_bound also holds: CheckpointCoordinator schedules the next trigger right after a trigger and retries every 500 ms while one is pending, so for a checkpoint-bound job the gap between triggers collapses to roughly the checkpoint duration and duration >= 0.8 * gap is a sound test. The normal user path reaches all of this.

1.2 Compatibility impact

Fully compatible for the new feature (additive; an engine without the endpoint just yields no checkpoint findings). One note: because this branch is stacked on #12631 (still open), the diff also carries that PR's default SEATUNNEL_API_BASE change from 5801 to 8080 (connectors.py). That is correct, but it also affects /run and metadata auto-detection for people who never use --diagnose; I described it in my review on #12631.

1.3 Performance and side effects

One more GET with a 10 s timeout; read-only; the response is bounded by MAX_RESPONSE_BYTES. The history is capped at 32 entries per pipeline, so the arithmetic is trivial.

1.4 Error handling and logging

Malformed input yields fewer findings rather than a crash, which is the right default. See Issue 2 for one gap in the notice.

Issues (all of them for this head)

Issue 1 (Medium, blocking): updatedAt is not the response time, so the "stalled checkpoint" rule cannot fire in the case it is meant for.

  • Location: diagnostics/checkpoints.py diagnose_checkpoints (the now_ms is None branch), used by _in_progress_findings and by the first_round_overdue gate in _counts_findings; engine side HazelcastCheckpointOverviewStateStore#updateOverview (calls snapshot.setUpdatedAt(System.currentTimeMillis()), only inside the update callback) and CheckpointMonitorService (updates happen on trigger, acknowledge, complete and fail).
  • Problem: updatedAt is the time of the last checkpoint event written to the overview, not the time the REST response was produced. For a checkpoint that is stuck waiting for the last subtask, the last write is the last acknowledgement, a few seconds after the trigger, and nothing is written afterwards. So age = updatedAt - triggerTimestamp stays at a few seconds and never reaches STALLED_CHECKPOINT_SECONDS. The error-level rule and the "first round overdue" gate stay silent exactly when a checkpoint hangs. The test test_the_overview_updated_at_is_preferred_over_the_local_clock uses an updatedAt that is 150 s after an in-progress trigger, a shape the engine cannot produce while the checkpoint is stuck, so it passes and pins the wrong behavior.
  • Risk: a hung barrier is reported as healthy. (The job-info diagnostics.generatedAt you already use in diagnose_job is different: JobRuntimeDiagnostics.build sets it at response time, so that one is correct.)
  • Fix: pass the same generatedAt (from the /job-info response, which was fetched moments earlier) as now_ms into diagnose_checkpoints, with the local clock as the fallback, and drop the updatedAt branch. Change the fixture to a realistic one (updatedAt a few seconds after the trigger, much older trigger relative to the injected "now") and assert the stalled finding still appears.
  • Raised by another reviewer: No (this corrects my own earlier suggestion).

Issue 2 (Medium, non-blocking): a cluster with the checkpoint monitor off still ends with "Nothing to report".

  • Location: cli.py run_diagnose (the except Exception notice) and CheckpointMonitorRestService#getOverview.
  • Problem: when the monitor service is not running, or has nothing recorded for the job, the engine answers HTTP 200 with only {"jobId": "..."} (no pipelines). That is not an exception, so the new "Checkpoint history unavailable ... monitor service is off" line is never printed, diagnose_checkpoints returns nothing, and the output can still end with "no rule matched this job's state". The new tests only cover the 404 case. This is the false-reassurance case from my previous Issue 4, now fixed for the exception path only.
  • Fix: also print the notice when the decoded response is not a dict or has no pipelines list (a short "no checkpoint data recorded yet" wording covers a fresh job as well), and add a test with 200 {"jobId":"852"}.
  • Raised by another reviewer: No.

Issue 3 (Low, non-blocking): the stalled threshold is above the default checkpoint timeout.

  • Location: STALLED_CHECKPOINT_SECONDS = 120 in diagnostics/checkpoints.py; packaged config/seatunnel.yaml sets checkpoint.timeout: 60000.
  • With the default timeout a hung checkpoint expires after 60 s and shows up as checkpoint_failing, so the stalled rule only matters when users raised checkpoint.timeout above 120 s. That is fine as a design choice, but please say so in the comment above the constant and in the README rule table so users on defaults know where to look.
  • Raised by another reviewer: No.

Carried over from #12631 (this branch contains that code unchanged). I posted the details in my review on #12631 and I am +1'ing them here rather than renumbering: an unknown or evicted job id is answered with HTTP 200 {"jobId":"<id>"} by JobInfoService and reads as "Nothing to report"; restore rules that treat FINISHED/CANCELED pipelines as "restarting again"; the default-port change being larger than the feature (suggested as its own small PR); redaction/size cap for the HTTP error body and a non-object JSON guard; the stale SEATUNNEL_API_BASE=http://localhost:5801 line in env.example.sh (still present at head, line 65); and the young-crash-loop wording. Please fix these once in #12631 and rebase this branch; I will not count them twice.

2. Code quality

  • Standards: license headers, docstrings that explain why, named thresholds with their reasoning, and the shared sort_findings / as_int instead of private imports. Good.
  • Tests: the new rule tests do exercise the changed behavior (for example test_old_failures_under_a_newer_completion_are_not_a_warning would fail if the lifetime-counter check came back, and test_checkpoints_getting_faster_are_not_reported_as_slower would fail if the newest-first assumption were reversed). Stability rating: Stable (injected clock, no sleeps, ephemeral ports). The one test I would change is the updatedAt one from Issue 1, and a monitor-off 200 case is missing (Issue 2).
  • CI: the apache-side checks on this head are all green (Build, Lint, Test with Python 3.10, Test with Python 3.13), and the matching fork run is success.
  • Docs: the EN and ZH README sections are updated and consistent; they will need the Issue 3 note.

3. Architecture

Reading the checkpoint series, the one place the engine publishes history, is the right design, and keeping the read best-effort is right too. The trend and ratio rules are well reasoned. The remaining gaps are the clock source (Issue 1) and a notice for the 200-but-empty case (Issue 2); both are small. Historical compatibility: compatible.

4. Issue summary

# Severity Location Summary Blocking
1 Medium checkpoints.py diagnose_checkpoints updatedAt is last-event time, so the stalled rule never fires Yes
2 Medium cli.py run_diagnose Monitor-off 200 response gets no notice No
3 Low checkpoints.py STALLED_CHECKPOINT_SECONDS Above the default 60 s checkpoint timeout, undocumented No
- Carried over #12631 items See my review on #12631 Yes, via #12631
- Merge state stacked on #12631 Merge order: #12631 first, then rebase this PR Process

5. Merge recommendation

Conclusion: Ready to merge after fixes

  1. Blockers: Issue 1, plus the carried-over blockers in #12631 (fix them there once).
  2. Recommended, non-blocking: Issues 2 and 3.

Merge state: the branch is mergeable with no conflicts now (19 commits behind dev, diverged only because of the stack and the squashed #12629, whose content GitHub still replays but is identical to dev). It cannot merge before #12631, so a rebase after that lands will shrink the diff. Please do not sync with dev just for CI: CI is already green on this head. I am a read-only reviewer, so my "changes requested" entry stays visible until a maintainer with write access dismisses it after the fixes.

Thanks again for the careful wire-format work, this is close.

SEZ9 added 2 commits October 11, 2026 10:04
Answers "why is this job not making progress?" from fields the engine
already publishes, with rules rather than a model.

The diagnostics block of /job-info carries per-state entry timestamps at
job and pipeline level plus the pipeline restore counter, so the two
questions users actually ask about a non-finishing job are arithmetic: a
pipeline restarting in a loop shows up as restoreCount climbing toward
maxRestoreCount, and "stuck for ages" is the age of the current state
entry. Both previously needed server logs to answer.

seatunnel_cli/diagnostics/jobs.py holds the rules as pure functions over
the response dict: failure (parsed through the existing parse_error),
crash loop, stuck before running, stuck tearing down, and a running job
whose source reads nothing or whose sink writes nothing.

The flag is handled before any provider setup, so it works with no API
key and no provider configured -- the situation someone is in when a job
is stuck in production. It is read-only: one GET, never a submit or a
stop. Exit status is non-zero only when the job itself is FAILED, so a
stuck-but-live job does not look like a command failure.
…history

The existing `--diagnose` rules all compare against zero or a fixed
threshold, which answers "did it break" and "is it stuck" but not the
question people actually ask about a long-running CDC job: it was fine at
first and now it lags. Such a job is RUNNING, both row counters keep
moving and restoreCount is 0, so the only finding today is the
informational "Running for 72h00m." line.

`/jobs/checkpoints/<id>` closes that gap because it is the one place the
engine publishes a series rather than a current value, so a job can be
compared against its own recent past. Six rules read it:

- checkpoints are taking longer than they did earlier in the history;
- checkpoint state is growing, which is usually what is behind that;
- a checkpoint takes about as long as the gap between triggers, so the
  job is checkpoint-bound. This one needs no baseline, so it still fires
  on a job that degraded before the retained window began;
- checkpoints are triggered but none ever complete;
- checkpoints are failing, with the engine's own failure reason;
- a checkpoint has been in progress far too long, naming how many
  subtasks have not acknowledged the barrier.

The read is best-effort: an engine without the endpoint, or a cluster
with the checkpoint monitor off, still gets the rest of the diagnosis.

Three details of the wire format decide whether the arithmetic is right,
and each one fails silently rather than loudly, so each has a test:
`history` is newest-first; failed checkpoints omit `durationMillis`
entirely; their `stateSize` is a primitive long and so arrives as a
plausible 0, which would turn growing state into shrinking state.

Also prints findings with markup disabled. Finding text is data, and
because "error" is a style name in the CLI theme, rich was consuming the
"[error]" severity prefix as a style tag -- severity reached the user by
colour alone, which is invisible in a pipe, in CI or under NO_COLOR.
@SEZ9
SEZ9 force-pushed the cli-diagnose-checkpoints branch from bcb55b4 to 7063bac Compare October 11, 2026 02:14
@SEZ9

SEZ9 commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @DanielLeens — and thank you for going back and checking updatedAt yourself. No apology needed: I took that suggestion and shipped it without verifying how the engine sets the field, so the dead rule was mine to have caught. It is a good reminder that "use the server's timestamp" is only safe once you know when the server writes it.

All three items are fixed at head 7063bacf, and the carried-over items are fixed in #12631 (now at d196f01b) with this branch rebased onto it.

1. updatedAt is last-event time, so the stalled rule could never fire (blocking) — fixed

Confirmed from source before changing it. setUpdatedAt(System.currentTimeMillis()) appears in exactly one place in the tree: inside the overviewMap.compute callback of HazelcastCheckpointOverviewStateStore.updateOverview, which CheckpointMonitorService calls on trigger, acknowledge, complete, fail and restore. So for a checkpoint hung on its last subtask the newest write is that last acknowledgement, nothing follows, and updatedAt - triggerTimestamp freezes a few seconds after the trigger. The error-level rule was unreachable in the one situation it exists for, and the first_round_overdue gate with it.

The updatedAt branch is gone. run_diagnose now resolves the engine's clock once from diagnostics.generatedAt on the /job-info response — which JobRuntimeDiagnostics.build stamps at response time, as you noted — and passes it into diagnose_checkpoints, with the local clock as the fallback inside each rule set. Both halves of the diagnosis therefore do their arithmetic in the same clock as the timestamps they subtract from, which was the point of the original suggestion and now actually holds.

The docstring records why updatedAt is not used, so the next person does not re-make the same inference from the field name.

Tests replaced: test_a_stuck_checkpoint_is_detected_even_though_updated_at_is_stale uses the realistic shape you described — updatedAt three seconds after the trigger, the trigger itself well past the threshold relative to the injected now — and asserts the stalled finding still appears. test_without_an_injected_clock_the_local_one_is_used_not_updated_at passes no now_ms at all, so it fails if anything starts consulting updatedAt again.

2. Monitor-off 200 response gets no notice — fixed

Confirmed: CheckpointMonitorRestService.getOverview builds {"jobId": ...} and returns it before adding updatedAt/pipelines when getMonitorService() is null or the overview is absent. No exception, so the except-only notice never ran.

The notice is now driven by whether the response is usable — a dict with a pipelines list — rather than by whether the request raised:

Job 852 my-job — RUNNING
  No checkpoint history for this job, so the slowdown checks did not run
  (the cluster may predate the endpoint, its monitor service may be off, or
  the job may not have checkpointed yet).

Your "fresh job" wording suggestion is in there, since that case is indistinguishable from the monitor being off at this level.

Two decisions in it worth flagging, both of which a test forced me to make explicit:

  • The notice is gated on a non-terminal job status, through the same is_non_terminal() helper [Feature][seatunnel-cli] Add --diagnose <jobId> to explain a stuck or failed job #12631 uses for the diagnostics notice. A finished or failed job legitimately has no checkpoint overview retained, so without the gate this fired on every terminal job. test_a_missing_checkpoint_endpoint_does_not_break_the_diagnosis now asserts the notice is absent there, with the live-job case covered separately.
  • "Nothing to report" is suppressed whenever a notice was printed. The two together would contradict each other, and the notice is the more truthful of the pair.

Tests: test_a_cluster_with_the_monitor_off_is_reported_not_passed_over uses 200 {"jobId": "852"} exactly as you asked, and test_a_healthy_job_with_no_checkpoint_data_does_not_look_fully_checked now asserts that "Nothing to report" does not appear.

3. Stalled threshold above the default checkpoint timeout — documented

Verified: packaged config/seatunnel.yaml sets checkpoint.timeout: 60000 against STALLED_CHECKPOINT_SECONDS = 120. The comment above the constant now says that on default settings a hung checkpoint expires first and surfaces as checkpoint_failing, so the rule earns its keep on clusters that have raised the timeout. Same note added to the rule list in both READMEs, so a user on defaults knows where to look.

Diff and CI

This branch is cut fresh from dev now that #12629 has merged, so the replayed commit is gone; the diff is 8 files, +3203/-0, and still carries #12631's commit until that lands, as the description says. Merge order unchanged: #12631 first, then this.

Locally: 327 tests pass, ruff check . clean with the pinned ruff==0.16.7. The engine-side facts above are from source reading; I did not run a cluster.

Ready for another look.

@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 for the quick turnaround, @SEZ9, and for confirming the updatedAt behaviour in the engine source instead of taking it on trust. I re-reviewed the whole diff at the latest head 7063bacf (static analysis against the engine source; I did not run the PR). My only blocker from the previous round, the unreachable checkpoint_stalled rule (my earlier Issue 1), is closed, and the carried-over #12631 items are fixed in the code that this branch contains. I found two small non-blocking items, listed below.

What problem does this PR solve?

  • Pain point: a long-running CDC job that slowly degrades stays RUNNING with moving counters and restoreCount 0, so --diagnose only printed "Running for 72h".
  • Approach: a best-effort second GET of /jobs/checkpoints/<id> and six rules over the checkpoint series (duration trend, state growth, checkpoint-bound ratio, never completed, failing, stalled), merged and sorted with the job-level findings.
  • In one sentence: --diagnose now compares a job with its own recent checkpoint history, so "it was fine and now it lags" gets an actionable answer.

1. Code change review

1.1 Core logic

seatunnel --diagnose <id> -> run_diagnose()                                   cli.py
  -> GET /job-info/<id>          -> diagnose_job(); diagnostics.generatedAt -> engine_now_ms
  -> GET /jobs/checkpoints/<id>  best effort; unusable (error, no `pipelines`) -> notice, rules skipped
       -> diagnose_checkpoints(overview, now_ms=engine_now_ms)
  -> sort_findings(job + checkpoint findings) -> markup=False + redact_credentials

Re-verified against the engine on dev:

  • Previous Issue 1 (clock) is fixed correctly. JobRuntimeDiagnostics.build stamps generatedAt with System.currentTimeMillis() at response time, and run_diagnose now passes it as now_ms (with the local clock as fallback). The updatedAt branch is gone and the docstring explains why it must not come back.
  • Previous Issue 2 (monitor-off 200) is fixed. The notice is now driven by "is the response a dict with a pipelines list", and gated on a non-terminal job. "Nothing to report" is suppressed when a notice was printed.
  • Previous Issue 3 (stalled threshold vs default timeout) is fixed in the constant's comment and in both READMEs.
  • Wire-format assumptions still hold: newest-first history (addFirst), durationMillis absent on failed entries, acknowledged / total in inProgress. Pending checkpoints are failed and removed from inProgress when a coordinator closes, so a finished job should not keep a phantom "stalled" entry.
  • Carried over from #12631, checked in this diff: unknown id (200 {"jobId"}, non-object body) now exits 1 with a clear message; the restore rules skip FINISHED/CANCELED, report FAILED only when exhausted, and the end-state check runs before the exhausted branch; the HTTP error body is redacted and clipped; the young-crash-loop wording now states only what one snapshot shows; the default-port change moved to #12722 (so connectors.py and env.example.sh are untouched here, as you said).

1.2 Compatibility impact

Fully compatible. The change is additive and read-only; an engine without the endpoint just gets one info line. No config options, defaults, protocols or serialization formats are touched.

1.3 Performance and side effects

One more GET with a 10 s timeout, bounded by MAX_RESPONSE_BYTES, and history is capped at 32 entries per pipeline, so the arithmetic is trivial. No retries, no state, nothing written.

1.4 Error handling and logging

Malformed input yields fewer findings rather than a crash. The checkpoint read failure is logged at debug and surfaced as a user-visible notice, which is the right split.

Issue 1 (Medium, non-blocking): the README still says the checkpoint rules use updatedAt.

  • Location: seatunnel-cli/README.md:360 and seatunnel-cli/README.zh-CN.md:316-317.
  • Problem: the bullet reads "the job rules use diagnostics.generatedAt, the checkpoint rules use updatedAt". That was true before this round, and it is exactly the claim that turned out to be wrong; the code and docstring now say the checkpoint rules also use diagnostics.generatedAt and deliberately avoid updatedAt.
  • Risk: the user-facing doc documents the bug that was just fixed, and invites someone to "restore" it.
  • Fix: say that both rule sets use diagnostics.generatedAt from the /job-info response, with the local clock as fallback, in both languages.
  • Raised by another reviewer: No.

Issue 2 (Medium, non-blocking): nothing tests that run_diagnose actually hands generatedAt to diagnose_checkpoints.

  • Location: seatunnel-cli/seatunnel_cli/cli.py (diagnose_checkpoints(checkpoints, now_ms=engine_now_ms)) and seatunnel-cli/tests/test_diagnose_cli.py.
  • Problem: the unit tests in test_diagnose_checkpoints.py pin the rule with an injected clock, but the only CLI test with an inProgress entry (test_a_checkpoint_error_outranks_a_job_level_info_line) has no diagnostics.generatedAt, so it runs on the local clock. If someone drops now_ms=engine_now_ms from that call, every test still passes, and the blocker fixed in this round regresses silently.
  • Fix: add one CLI test where generatedAt is _NOW and the in-progress trigger is, say, _NOW - 10_000 (not stalled by the engine clock, but hugely stalled by the real local clock), and assert no checkpoint_stalled line; plus the mirror case at _NOW - 150_000 that must report it.
  • Raised by another reviewer: No.

2. Code quality

  • Standards: license headers present, docstrings explain why, thresholds are named with reasoning, no private cross-module imports. Good.
  • Tests: the new rule tests exercise the changed behaviour (for example test_a_stuck_checkpoint_is_detected_even_though_updated_at_is_stale fails if updatedAt is used again; test_old_failures_under_a_newer_completion_are_not_a_warning fails if the lifetime-counter check returns). No test weakening against the base. Stability rating: Stable (injected clocks, loopback server on an ephemeral port, no sleeps; the one time.time() use is the intentional local-clock-fallback test). The only gap is Issue 2.
  • CI on this head: all green apache-side: Build, Lint, Test with Python 3.10, Test with Python 3.13.
  • Docs: EN and ZH are consistent with each other; both need the Issue 1 correction.

3. Architecture

A precise fix at the right layer: pure rule functions over the engine's own series, one thin I/O seam in run_diagnose, shared sort_findings / as_int. Historical compatibility: compatible.

4. Issue summary

# Severity Location Summary Blocking
1 Medium README.md:360, README.zh-CN.md:316-317 Docs still say checkpoint rules use updatedAt No
2 Medium cli.py run_diagnose, test_diagnose_cli.py generatedAt plumbing into the checkpoint rules is untested No

5. Merge recommendation

Conclusion: Ready to merge

  1. Blockers: none. My previous blocker (the stalled-rule clock) is fixed and CI was never a blocker here.
  2. Recommended, non-blocking: Issues 1 and 2; both are small and local, and I would take them in this PR.

Merge state: mergeable=true with no conflicts (2 ahead, 11 behind dev; the seatunnel-cli changes on dev since the merge base are three one-line edits and do not overlap). BLOCKED is only the required approval. This PR is stacked on #12631, so it cannot land before that one; the diff will shrink once it does. Please do not sync with dev just for CI, which is already green. I am a read-only reviewer, so my earlier "changes requested" entries stay visible until a maintainer with write access dismisses them.

Thanks again, the wire-format work and the way you chase down each assumption in the engine source are really appreciated.

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

Thank you @SEZ9 for this contribution, and for the checkpoint-history slowdown diagnosis, a very practical tool for operators troubleshooting long-running jobs.

CI is green on the current head and the code-side review has no remaining blockers, so I am approving. Really appreciate the time and care you put into this PR - contributions like this make SeaTunnel better for everyone. Looking forward to more from you!

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] Diagnose gradual slowdown of long-running jobs from checkpoint history

3 participants