Skip to content

[Improve][Zeta] Apply the finished-jobs page before the per-job metrics and DAG lookups - #12130

Merged
davidzollo merged 4 commits into
apache:devfrom
awsomesud347:fix-12123-history-listing
Sep 14, 2026
Merged

davidzollo merged 4 commits into
apache:devfrom
awsomesud347:fix-12123-history-listing

Conversation

@awsomesud347

@awsomesud347 awsomesud347 commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Part of #12123, a sub task of #12126. It does not close that issue, for the reason given at the
end of this section.

The issue asks which REST API reaches JobHistoryService.getJobStatusData(), and how often. The
answer is GET /metrics and GET /openmetrics, once per Prometheus scrape on the master. The
chain runs from MetricsServlet into NodeExtension.getMetricFamilySamples(), which collects
from JobMetricExports, which calls CoordinatorService.getJobCountMetrics(), which calls
getJobStatusData(). The only other caller is the CLI, which is one shot per invocation. The job
listing endpoints do not reach getJobStatusData() at all, because JobInfoService reads the
IMaps directly.

Measuring that turned up something the issue did not anticipate. The expensive scan was not in
getJobStatusData(), it was in the finished job listing, and that is what this pull request
fixes.

JobInfoService.getJobsByStateJson fetched every retained job, filtered and sorted it, then
performed two IMap point lookups and a metric aggregation for each one, before
PageBaseServlet.writeJsonWithPagination discarded everything outside the requested page. A
request for ?page=1&rows=10 against N retained jobs cost one full scan, two point lookups per
stored job, and a metric aggregation per stored job. The page and rows parameters bounded the
size of the response but not the work done to produce it.

A new overload, getJobsByStateJson(state, start, rows), applies the page before those lookups,
so a paged request pays them only for the rows it returns. Measured with JMH against a seeded
finished job IMap, average time per operation:

Retained jobs Before After Improvement
1,000 905,705 ± 50,938 us/op 24,218 ± 1,004 us/op 37.4x
10,000 9,233,153 ± 673,522 us/op 157,430 ± 16,030 us/op 58.6x

Allocation from the same run, with -prof gc:

Retained jobs Before After Reduction
1,000 1,172 MB/op 29.9 MB/op 39.1x
10,000 12,761 MB/op 211 MB/op 60.3x

In wall clock terms, a first page request against ten thousand retained jobs drops from about 9.2
seconds to about 0.16 seconds, and allocates 211 MB rather than 12.7 GB. The bundled Web UI polls
this endpoint every five seconds.

This is deliberately narrow. I also tried making getJobCountMetrics() count without building the
listing, and measured no benefit: 0.19% latency difference with overlapping error bars, and 198.66
against 198.71 MB allocated per operation. I dropped it rather than add API surface for an
unmeasured change.

That leaves the getJobStatusData() scan untouched, which is why this says part of rather than
closes. Counting ten thousand retained jobs allocates roughly 200 MB per Prometheus scrape, almost
entirely from deserialising JobState values. Fixing that means avoiding the fetch to the master
rather than avoiding allocation from it, which is a different change from this one.

One cost this PR does not remove, for the record. matchingJobStates() still fetches, deserialises
and sorts every retained JobState on each request. Only the per-row work became lazy, so a paged
request now pays two IMap point lookups and a metric aggregation per returned row rather than per
stored row, but the scan and sort ahead of that still scale with retention. That is the same shape
of cost as the metrics path above, and it is better addressed by not pulling those values to the
master at all than by slicing afterwards.

Retention and TTL are untouched, since that belongs to #10767.

Does this PR introduce any user-facing change?

No, with one deliberate exception. Response shapes, parameter names and existing error messages
are unchanged, and the unpaged getJobsByStateJson(String) overload is kept so the older text
command REST path returns the same payload as before.

The exception is input validation, which is deliberate and was requested in review. page and
rows are now validated on /finished-jobs/:state, /running-jobs and /running-jobs/summary,
since all three go through PageBaseServlet and the latter two are served by the same
RunningJobsServlet instance. A value that is not an integer, or is not greater than 0, is
rejected with a message naming the parameter. A page whose start offset would overflow a 32 bit
integer is also rejected, where previously it could wrap to a small positive offset and silently
return the wrong page.

Concretely, rows=0 was previously accepted and returned an empty page, and a negative rows
produced an internal error. Both now return 400. This is recorded in incompatible-changes.md and
in the REST docs in both languages.

How was this patch tested?

Two tests were added to JobInfoServiceNullSafetyTest for the service overload.

shouldApplyPageBeforePerJobLookups seeds twenty five finished jobs, requests the first ten, and
verifies that exactly ten metric lookups and ten DAG lookups occurred. Asserting only on the
returned JSON would still pass if the whole listing were built and then sliced, so the test
asserts the lookup count instead.

shouldReturnNewestFinishedJobsFirst checks that ordering by finish time descending is preserved,
so paging over a growing history stays stable.

Nine tests were added in a new FinishedJobsServletTest for the servlet surface, covering zero and
negative rows, a non integer value, a page below 1, an offset that overflows an int, a page
starting beyond the end of the results, a page starting exactly at total, and the routing between
the paged and unpaged service calls.

Making the servlet testable required widening JobInfoService.JobPage's constructor from private
to public, because it is a final class that Mockito cannot stub. It is an immutable value type
already returned by a public method so this seemed reasonable, but flagging it since it was not
asked for.

mvnw test -pl seatunnel-engine/seatunnel-engine-server passes with 470 tests, no failures and no
errors. spotless:apply and mvnw -DskipTests verify are clean.

The timing and allocation figures came from the same run of the seatunnel-benchmarks JMH harness
at its BenchmarkBase defaults, three forks with three warmup and five measurement iterations,
with -prof gc. The benchmark code itself is not included here. Note that the harness cannot
currently run on Windows, because the
mini cluster home path created at SeaTunnelEnvironmentContext.java:103 is emitted into a double
quoted YAML scalar where Windows backslashes read as escape sequences. I ran these under WSL and
intend to send that fix as its own pull request.

Check list

  • No new Jar binary package is added by this pull request.
  • Documentation is updated: the REST API docs in English and Chinese, and an
    incompatible-changes.md entry in both languages.
  • incompatible-changes.md records the pagination validation change under ## dev.
  • This is not a connector change, so the connector checklist does not apply.

@awsomesud347
awsomesud347 force-pushed the fix-12123-history-listing branch from 85ecc58 to 96805de Compare September 5, 2026 19:37
@awsomesud347 awsomesud347 changed the title [Improve][Zeta] Avoid materializing all retained jobs for counts and paged listings [Improve][Zeta] Apply the finished-jobs page before the per-job metrics and DAG lookups Sep 5, 2026
@awsomesud347
awsomesud347 marked this pull request as ready for review September 5, 2026 19:38

@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 contribution, and welcome to Apache SeaTunnel! This is a clean, well-scoped improvement, and it's great to see it land with a dedicated regression test — nice work for a first PR.

What Problem Does This PR Solve?

GET /finished-jobs/:state?page=&rows= previously built the entire finished-jobs listing — including the per-job metrics lookup (getFinishedJobMetricsJson) and the per-job DAG lookup (getFinishedJobDAGInfo) — for every job matching the state filter, and only sliced the resulting JsonArray down to one page afterwards (PageBaseServlet#writeJsonWithPagination, unchanged). That means a UI asking for page 1 of 10 rows out of a history of thousands of finished jobs still paid two IMap point-lookups and a metrics aggregation for every one of those thousands of rows, just to throw away all but 10.

This PR reorders the work: the finished-job listing is first filtered/sorted into a lightweight List<JobState> (matchingJobStates), the page is sliced from that list, and only then are the per-job metrics/DAG lookups (toJobInfoJson) performed — one time each, only for the rows actually returned.

Core Logic Analysis / Runtime Path Trace

FinishedJobsServlet#doGet → JobInfoService#getJobsByStateJson

Before:

public JsonArray getJobsByStateJson(String state) {
    ...
    return finishedJob.values().stream()
        .filter(...).sorted(...)
        .map(jobState -> getJobInfoJson(jobState, getFinishedJobMetricsJson(jobId), getFinishedJobDAGInfo(...)))  // done for ALL matches
        .collect(...);
}
// FinishedJobsServlet: writeJsonWithPagination(req, resp, jobInfoService.getJobsByStateJson(state)); // sliced AFTER

After (JobInfoService.java:119-166, FinishedJobsServlet.java:53-63):

public JobPage getJobsByStateJson(String state, int start, int rows) {
    List<JobState> matches = matchingJobStates(state);            // filter+sort only, no per-job lookups
    JsonArray data = matches.stream().skip(start).limit(rows)
        .map(js -> toJobInfoJson(js, finishedJobDAGInfo))         // lookups only for the page
        .collect(...);
    return new JobPage(data, matches.size());
}

FinishedJobsServlet now branches on whether page was requested (pageParams(req)); when present, it calls the new two-arg overload and writes {"data":..., "total": matches.size()} via writeJsonPage. When absent, it still calls the original no-arg getJobsByStateJson(state) (now implemented in terms of the shared matchingJobStates + toJobInfoJson, functionally identical to the old inline stream) and writes the raw array, exactly as before.

I verified the filter predicate (state match, nonNull) and sort comparator (finishTime, nulls-last, reverse order → newest first) are byte-for-byte the same as the pre-existing implementation, just factored into matchingJobStates. The total returned is matches.size(), i.e. the count of all state-matching jobs before slicing — identical semantics to the old jsonArray.size() computed before pagination. So this is a genuine "reduce point-lookup cost without changing results" fix, not a change in what is returned.

Compatibility Classification: Fully compatible

  • Response envelope for the paged path is unchanged: {"data": [...], "total": n} (docs/en/engines/zeta/rest-api-v2.md:779-787 already documents page/rows for this endpoint; no doc change needed).
  • Non-paged path (page param absent) returns the same raw JsonArray as before.
  • total still means "count of all state-matching finished jobs," not "count in this page" — same as before.
  • Page-out-of-range validation (start > total ⇒ IllegalArgumentException) and page < 1 validation are preserved, just split between pageParams() and the new checkPageInRange().

Side-Effect Analysis

  • Positive: for a paged request, the number of IMAP_FINISHED_JOB_METRICS and IMAP_FINISHED_JOB_VERTEX_INFO point-lookups drops from O(matching jobs) to O(page size) — confirmed by the new shouldApplyPageBeforePerJobLookups test, which asserts verify(finishedJobMetricsMap, times(10))/verify(finishedJobVertexInfoMap, times(10)) against a 25-job dataset. This is the actual perf win and it's the right thing to assert (asserting only on output JSON would pass even without the fix).
  • No new locks/threads/network calls introduced; matchingJobStates still does a single pass over finishedJob.values() (an IMap snapshot), same as before — no extra IMap round-trip.
  • Non-paged path is unaffected in cost (still O(all matching jobs)), which is expected since it must return the whole set.

Error Handling & Logging

No behavioral change to the per-job metrics/DAG exception handling (getFinishedJobMetricsJson/getFinishedJobDAGInfo still swallow-and-fallback exactly as before, per the untouched shouldListFinishedJobsWhenFinishTimeMetricsOrDagAreMissing test). No new logging added or needed here.

Test Coverage: adequate

Two new focused unit tests in JobInfoServiceNullSafetyTest:

  • shouldApplyPageBeforePerJobLookups — proves the core claim (lookup count == page size, not total matches).
  • shouldReturnNewestFinishedJobsFirst — pins down ordering semantics across a page boundary.

Both are deterministic, mock-based, and test behavior rather than implementation incidentals. No E2E test was added, but none is needed here — this is a pure internal ordering/perf change with no observable REST contract change, and the existing REST-level finished-jobs E2E coverage already exercises the endpoint.

CI Diagnosis

The "Build" check on apache/seatunnel shows action_required with the message "Workflow run detection failed... unable to detect the workflow run for testing the changes in your PR." I checked awsomesud347/seatunnel's Actions runs directly for head SHA 96805dee19 — there are zero workflow runs recorded for that commit in the fork. This is the well-known pattern where GitHub Actions has not been enabled on a first-time contributor's fork, so the apache-side pointer check can never find a corresponding fork run to dereference. This is an environmental/fork-configuration issue, not caused by this PR's diff.

@awsomesud347 — to fix this, please enable GitHub Actions on your fork (Settings → Actions → "I understand my workflows, go ahead and enable them") and then push a new commit (an empty commit works fine, e.g. git commit --allow-empty -m "trigger CI") to re-trigger the build.

Issue Summary

# File:Line Issue Severity Raised by another reviewer
— — No blocking issues found in the diff. — No

Optional, non-blocking idea for a future PR: RunningJobsServlet still uses the older writeJsonWithPagination, which slices after building the whole array. If running-job listing/metrics ever becomes a hot path at scale, the same "slice before per-row work" technique introduced here could be applied there too — not something this PR needs to solve.

Merge Recommendation: Approve

The change is minimal, behavior-preserving on every path except the intended perf improvement, backward compatible at the REST contract level, and comes with tests that actually prove the claimed fix rather than just re-asserting the output. The failing "Build" check is a fork configuration issue (Actions not enabled), unrelated to the code — please enable Actions and push an empty commit to get a green run before this is merged.

Blockers

None from a code-review standpoint. The only outstanding item before merge is getting a real CI run (see CI Diagnosis above).

Recommended Fixes

  1. Enable GitHub Actions on your fork and push a commit to trigger a real CI run.
  2. (Optional, not required) Consider applying the same slice-before-lookup pattern to RunningJobsServlet in a follow-up if running-job listing ever needs it.

Thanks again for the contribution — this is a solid first PR, and I'd be glad to take another look once CI is green. Looking forward to more contributions from you!

@davidzollo davidzollo added the First-time contributor First-time contributor label Sep 6, 2026
@awsomesud347

Copy link
Copy Markdown
Contributor Author

@DanielLeens CI is green now. You were right about the cause.

The first run had one failure. PaimonSinkCDCIT hit an Awaitility timeout while waiting for
container threads to drain on teardown. The JDK 11 job passed on the same commit, and JDK 8 passed
on a rerun with no code change.

Your approval predates the empty commit I pushed to trigger CI, so GitHub is showing review
required on the current head. Ready for another look whenever suits you.

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

What Problem Does This PR Solve?

  • User pain point: GET /finished-jobs/:state?page=&rows= used to build the entire finished-jobs listing - including a per-job metrics lookup and a per-job DAG lookup for every job matching the state filter - and only sliced the result down to one page afterwards. A UI asking for page 1 of 10 rows out of a history of thousands of finished jobs still paid thousands of IMap point-lookups and metrics aggregations just to throw almost all of them away.
  • Fix approach: Reorder the work so the finished-job listing is first filtered/sorted into a lightweight list of job states, the page is sliced from that list, and only then are the per-job metrics/DAG lookups performed - one time each, only for the rows actually returned.
  • One-sentence summary: A clean, well-scoped improvement with a dedicated regression test that proves the actual perf claim (lookup count, not just output shape).

First, welcome back, and thank you for following through on enabling Actions and pushing the trigger commit - and for the clear write-up on why the JDK 8 leg needed a rerun. You were right that it was a fork-configuration gap, not anything in the diff, and I appreciate you closing the loop with the actual root cause (PaimonSinkCDCIT Awaitility teardown timeout) rather than just saying "it passed now."

Re-review scope and what actually changed

You're right that GitHub shows "review required" because my prior approval was recorded against 96805dee19, and the head is now 441455e556 (the "trigger CI" commit). I didn't want to just wave that through on the assumption that nothing changed, so I re-pulled the current head into a clean worktree and diffed it against the commit I originally reviewed:

git diff --stat 96805dee1934da973893060cd7b676fc96e1e001 441455e5569482a084734cc365493a0d17f5bda2
(no output - zero files changed)

Confirmed: 441455e556 is a genuinely empty commit (git show --stat shows no file changes), exactly what it says on the tin - a trigger-CI commit. So this re-review is a full fresh pass over the same code I approved before, not a review of new logic, and I re-read every changed file end to end rather than trusting my earlier notes:

  • JobInfoService.java (getJobsByStateJson(String, int, int), the new matchingJobStates/toJobInfoJson split, and the JobPage holder) - the filter predicate (state match, non-null) and sort comparator (finishTime, nulls-last, reverse order = newest first) are unchanged from the pre-existing single-method implementation, just factored so the per-job lookups (toJobInfoJson) run only over the post-skip/limit slice instead of over every match.
  • FinishedJobsServlet.java - branches on pageParams(req); when present, calls the new paged overload and writes {"data":..., "total": matches.size()}; when absent, still calls the original no-arg getJobsByStateJson(state) (now built from the same matchingJobStates/toJobInfoJson helpers, functionally identical to the old inline stream) and writes the raw array, exactly as before.
  • PageBaseServlet.java - the new pageParams() + checkPageInRange() pair reproduces the old writeJsonWithPagination's validation exactly: page < 1 still throws "Page number must be greater than 0", and start > total still throws "Page number exceeds total pages" (not >=, so an empty result set with page=1 still doesn't throw - same as before). writeJsonPage writes the identical {"data": [], "total": n} envelope. I checked this boundary condition specifically since it's exactly the kind of off-by-one a page-splitting refactor could introduce, and it didn't.
  • JobInfoServiceNullSafetyTest.java - shouldApplyPageBeforePerJobLookups builds 25 job states, requests a 10-row page, and asserts both page.getData().size() == 10 and, critically, verify(finishedJobMetricsMap, times(10)) / verify(finishedJobVertexInfoMap, times(10)) - this is the right assertion because a broken "slice after building everything" implementation would still pass an output-shape-only test. shouldReturnNewestFinishedJobsFirst pins down ordering across a page boundary. Both are deterministic, mock-based (Mockito over IMap), with no sleeps, no shared static state between tests (fresh mocks in @BeforeEach), and no order dependence.

Everything here matches what I verified in my first review; re-verifying against the actual current file contents (not just re-reading my old notes) didn't turn up anything I'd missed the first time.

Example of the before/after behavior difference

Requesting GET /finished-jobs/FINISHED?page=1&rows=10 against a history of 10,000 finished jobs: before this PR, the server did ~10,000 IMAP_FINISHED_JOB_METRICS/IMAP_FINISHED_JOB_VERTEX_INFO lookups and metrics aggregations, then returned 10 rows. After this PR, it does exactly 10 of each lookup. The JSON response shape, the total field's meaning (count of all state-matching jobs, not just this page), and the non-paged path (page omitted) are all unchanged.

Compatibility Impact: Fully compatible

Same conclusion as before, re-verified: paged response envelope unchanged, non-paged path returns the same raw JsonArray, total semantics unchanged, and both page-number and page-range validation are preserved (traced through pageParams/checkPageInRange above). No REST contract, config option, or serialization format changes.

Performance / Side-Effect Analysis

The perf win is real and specifically tested, not just implied - see shouldApplyPageBeforePerJobLookups above, which is the correct way to test this (asserting call counts against the mocked IMaps, not just the returned JSON). No new locks, threads, or extra IMap round-trips: matchingJobStates still does a single pass over finishedJob.values().

Error Handling and Logging

No behavioral change to the per-job metrics/DAG exception handling (getFinishedJobMetricsJson/getFinishedJobDAGInfo still swallow-and-fall-back exactly as before; shouldListFinishedJobsWhenFinishTimeMetricsOrDagAreMissing remains untouched and still passes). No new logging needed here.

Test Coverage and Test Stability

Coverage is adequate and targeted: the two new tests prove the specific claims of this PR (lookup count reduced to page size; ordering preserved across a page boundary) rather than re-asserting incidental output. No E2E test was added, and none is needed - this is an internal ordering/perf change with no observable REST contract change, and existing finished-jobs E2E coverage already exercises the endpoint end to end.

Stability rating: Stable - no sleeps, no timing assumptions, no shared mutable state across tests, in either the new tests or the ones I re-checked around them.

Documentation Updates

No doc changes needed and none were made - the paged response envelope ({"data": [...], "total": n}) was already documented for this endpoint before this PR, and nothing about that contract changed.

CI Diagnosis (current)

Build is green as of the current head (441455e556) - I confirmed this directly against apache/seatunnel's check-runs, not just by trusting the comment. Your explanation matches what a Build check pointing at a fork's own Actions run would show: PaimonSinkCDCIT hitting an Awaitility timeout waiting for container threads to drain on teardown is a known category of Testcontainers-teardown flake in this connector's IT suite, unrelated to anything touched by this diff (this PR doesn't go near Paimon, CDC, or container lifecycle code), and a same-commit rerun clearing it on the JDK 8 leg while JDK 11 passed on the first try is consistent with that being environmental rather than code-caused.

Issue Summary

# File:Line Issue Severity Raised by another reviewer
- - No blocking issues found. - No

Optional, non-blocking idea for a future PR (carried over from my first review, still true): RunningJobsServlet still uses writeJsonWithPagination, which slices after building the whole array. If running-job listing/metrics ever becomes a hot path at scale, the same "slice before per-row work" technique from this PR could be applied there too - not something this PR needs to solve.

Merge Recommendation: Approve

The diff I'm approving now is, byte for byte, the same diff I approved before (verified above via git diff --stat against the previously-reviewed commit, plus a full fresh read of every changed file and the tests), and CI is now green for real, with a well-explained, unrelated flake accounting for the one red run along the way. This remains minimal, behavior-preserving outside the intended perf fix, backward compatible, and backed by tests that actually prove the claimed improvement.

Blockers

None.

Recommended Fixes

None required. The RunningJobsServlet note above is a nice-to-have for a future PR, not this one.

Thanks again for a genuinely solid first contribution, and for tracking down the real cause of the flaky CI leg instead of just rerunning until green - that's exactly the kind of diligence that makes a PR easy to trust. Looking forward to more from you.

@SEZ9

SEZ9 commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Thanks @DanielLeens for the careful re-review, and especially for re-pulling the head into a clean worktree and confirming that git diff --stat 96805dee1934da973893060cd7b676fc96e1e001 441455e5569482a084734cc365493a0d17f5bda2 produces no output. That settles that 441455e556 is a pure trigger-CI commit and that the code under review is identical to what was approved at 96805dee19.

Because the diff between those two commits is empty, though, it also means none of the points from my earlier pass have moved in the meantime. Before I'm comfortable merging I'd like to close the loop on each of them explicitly (either a code change or a short "won't fix, because…" is fine):

  1. pageParams() / getStart() input validation (PageBaseServlet) – page is validated but rows is not, and getStart() multiplies two caller-controlled ints. Overflow can wrap to a small positive value that slips past checkPageInRange and silently serves the wrong page, and other bad input surfaces as raw JDK exceptions rather than the endpoint's own error message. Please validate rows alongside page and compute the start offset in a way that rejects overflow with the servlet's error response.
  2. checkPageInRange boundary (PageBaseServlet) – it uses start > total, so a page starting exactly at total returns an empty page instead of being rejected. Could you confirm whether this is intentional and matches what the legacy writeJsonWithPagination did? If they differ, please align them (or call out the change).
  3. Duplication with writeJsonWithPagination() (PageBaseServlet) – parsing/validation now lives in two places used by different servlets. Ideally the pre-existing path is routed through the new pageParams()/checkPageInRange() helpers so there is a single source of truth for pagination semantics.
  4. getJobsByStateJson(state, start, rows) preconditions (JobInfoService) – the new service-level overload has no argument checks and relies on Stream internals to fail. A couple of explicit precondition checks with clear messages would make it safe for any future caller, not just FinishedJobsServlet.
  5. Docs (FinishedJobsServlet) – the pagination behaviour of GET /finished-jobs/:state changes (source-side slicing, new out-of-range semantics), but there is no REST API documentation or release-note update. Please add a short note covering the new behaviour.
  6. Test coverage – the added tests in JobInfoServiceNullSafetyTest exercise the service overload directly, but the servlet-side surface (pageParams, checkPageInRange, writeJsonPage, and the FinishedJobsServlet wiring) is untested. A servlet-level test that covers the invalid-rows, overflow and boundary cases from points 1–2 would be very welcome.
  7. matchingJobStates() cost (JobInfoService) – it still materializes, deserializes and sorts every retained JobState per request; only the per-row lookups became lazy. I'm fine with that as a follow-up given the scope of this PR, but please mention it in the description so the remaining cost is documented.

If you'd prefer to split items 3 and 7 into follow-up PRs, just say so and I'll track them separately; the rest I'd like addressed here. Once a new commit lands I'll do another pass promptly.

@nzw921rx

nzw921rx commented Sep 7, 2026

Copy link
Copy Markdown
Member

May I ask if there has been an improvement in benchmark testing CV error and score? Do we need to add this to the existing seam bench marks? For the convenience of comparing and optimizing the results

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@SEZ9 thanks for the list. Taking all seven here, not splitting 3 or 7.

Addressing Item 2: It is intentional. The legacy
writeJsonWithPagination used start > total || page < 1, so a page starting exactly at total
returned an empty page rather than being rejected, and checkPageInRange preserves that. I plan to add a code comment recording it rather than change the behaviour. Let me know if you would rather have it rejected.

Also, item 3 will entail that /running-jobs picks up the rows validation from item 1, so
input that endpoint previously accepted will start returning 400. I will cover it in the REST docs
and add an entry to incompatible-changes.md.

@nzw921rx yes, I will add them to seatunnel-benchmarks. On the margins, the numbers I posted are weak because I ran with -f 1 -wi 1 -i 3 to save time, which gave relative errors between 15 and 43 percent. The gap is wide enough that the conclusion holds, but they are not solid enough to track against over time. I am re-running with the module's BenchmarkBase defaults and will post the tighter figures.

The rest are code changes. I will push them as a single commit and comment again once CI is green.

@nzw921rx

nzw921rx commented Sep 7, 2026

Copy link
Copy Markdown
Member

@awsomesud347 Thank you for your reply. I think the benchmark test should be submitted separately from this PR, so that it can be compared with the dev baseline to verify the optimization effect. If it is significantly improved, the evaluation criteria of the benchmark will become an asset of the project. Thank you for your work, which has taken a solid step towards improving the performance and stability of the engine, and enabled performance optimization to be driven by reproducible evidence🚀

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@nzw921rx happy to split them out. But need to make a decision on something as it changes how the comparison works.

The two benchmarks are finishedJobsFirstPageOld, which calls the existing getJobsByStateJson(state), and finishedJobsFirstPageNew, which calls the getJobsByStateJson(state, start, rows) overload this PR adds. The second will not compile against dev. The first does compile, but this PR only refactors that method so it shares its filter and sort with the new overload, it does not make it faster. So a benchmark PR run against dev alone would show no improvement, which I do not think is what you are after.

Two ways to get a real baseline comparison:

  1. Benchmark the servlet rather than the service, driving FinishedJobsServlet.doGet with page and rows set. On dev that path builds the whole listing and slices afterwards, so the same benchmark gets faster once this PR merges and the before and after is genuine. It also measures what callers actually hit. Needs a small fake request and response in the harness.
  2. Land the benchmark PR after this one, where both methods exist and a single run compares them directly.

I lean towards 1, since it stays useful as a regression check on the endpoint afterwards. Happy to do either. Which would you prefer?

@nzw921rx

nzw921rx commented Sep 7, 2026

Copy link
Copy Markdown
Member

@nzw921rx happy to split them out. But need to make a decision on something as it changes how the comparison works.

The two benchmarks are finishedJobsFirstPageOld, which calls the existing getJobsByStateJson(state), and finishedJobsFirstPageNew, which calls the getJobsByStateJson(state, start, rows) overload this PR adds. The second will not compile against dev. The first does compile, but this PR only refactors that method so it shares its filter and sort with the new overload, it does not make it faster. So a benchmark PR run against dev alone would show no improvement, which I do not think is what you are after.

Two ways to get a real baseline comparison:

  1. Benchmark the servlet rather than the service, driving FinishedJobsServlet.doGet with page and rows set. On dev that path builds the whole listing and slices afterwards, so the same benchmark gets faster once this PR merges and the before and after is genuine. It also measures what callers actually hit. Needs a small fake request and response in the harness.
  2. Land the benchmark PR after this one, where both methods exist and a single run compares them directly.

I lean towards 1, since it stays useful as a regression check on the endpoint afterwards. Happy to do either. Which would you prefer?

I understand that if it is a newly added method, it may not be possible to compare through a stable dev baseline, and there may not be a need to submit a benchmark PR. So, I have a question to ask you? The specific steps of your benchmark testing, I understand that the bottlenecks we have tested so far are all in IMAP. It seems that pagination cannot speed up IMAP operations, resulting in fluctuations and large confidence intervals for CV errors. Do you have identified any issues with flame graphs, JFR graphs, or optimized GC? I am very puzzled about the optimization effect described in the PR, as it seems to have improved many times faster. However, I am more confused about which aspect of improvement has been sacrificed.

@nzw921rx

nzw921rx commented Sep 7, 2026

Copy link
Copy Markdown
Member

#11494
Can this PR solve the optimization problem you are currently facing?😄
I think you can also test locally and pay attention to it🚀

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@nzw921rx These are fair questions, and you are right that the scan itself is untouched.

Let me start with why the old code was shaped this way, because it explains the size of the gap. The service method getJobsByStateJson(String state) takes no page arguments at all, so it has no notion of a page. Pagination lives one layer up, in PageBaseServlet, which could only slice the array after the service had already built every row. The service was therefore always doing the full amount of work regardless of how few rows the caller asked for.

You are correct that pagination cannot speed up the scan, and it does not. matchingJobStates() is shared by both paths and performs the same values() fetch, the same filter and the same sort either way. What changed is the per-row work that happens after the scan. For each job, toJobInfoJson performs two IMap point lookups, a getOrDefault on IMAP_FINISHED_JOB_METRICS and a get on IMAP_FINISHED_JOB_VERTEX_INFO, and then builds the row through getJobInfoJson, which calls getJobMetrics and allocates a fresh ObjectMapper in order to readTree the metrics JSON at BaseService.java:684. At ten thousand retained jobs with rows=10, the old path performed twenty thousand point lookups and ten thousand metric aggregations and then discarded everything except ten rows. The new path performs twenty and ten. So pagination does reduce IMap operations, just not the scan.

That is also the answer to what was sacrificed, which is nothing. This is not a trade of one cost against another. The old path was building rows that were thrown away microseconds later, and the change simply stops building them. The output is identical in content, ordering and total. The one genuine cost is that matchingJobStates() now collects into a List before mapping, which the previous code did not do, so the unpaged path allocates one additional list.

The evidence I find most convincing is not a timing measurement at all. The test JobInfoServiceNullSafetyTest#shouldApplyPageBeforePerJobLookups seeds twenty five finished jobs, requests the first ten, and then asserts that exactly ten metric lookups and ten DAG lookups occurred. Because that is a counted invariant rather than a duration, it is unaffected by confidence intervals, JIT warmup or garbage collection.

On the specific steps, the measurement used the existing seatunnel-benchmarks JMH harness rather than anything new. IMapJobGrowthBenchmarkWorkload starts a single member mini cluster, runs a real fixture job to completion so that the stored values are genuine Zeta objects, and then seeds initialStoredJobCount additional finished jobs into IMAP_FINISHED_JOB_STATE and IMAP_FINISHED_JOB_METRICS. I parameterised that at one thousand and ten thousand. Two benchmarks then ran against that same seeded state, one calling the paged overload and one calling the unpaged method, in AverageTime mode reported in microseconds. I ran it under WSL because the harness cannot start on Windows, where the mini cluster path is written into a double quoted YAML scalar and the backslashes are read as escape sequences.

There are two caveats on those numbers that you should weigh. The first is that the baseline benchmark calls the refactored getJobsByStateJson(state) on this branch rather than the version on dev, so the ratio compares the unpaged and paged paths within one branch rather than dev against this PR. The second is that preloadStoragePressure stores the same JobState instance under every key, which means jobState.getJobId() returns the same identifier for all seeded rows and the metrics lookup therefore hits a single key repeatedly. Real traffic would spread across distinct keys and partitions, so the absolute figures are optimistic even though the ratio holds.

On profiling, there is no flame graph or JFR yet. The only -prof gc run so far was against the counting benchmarks rather than these listing ones, so allocation data for this path is still missing. I am re-running now at the module's BenchmarkBase defaults with -prof gc added, which should show allocation falling in step with the lookup count, and I will post those figures.

The wide confidence intervals were caused by my settings rather than by the workload. I ran with one fork, one warmup iteration and three measurement iterations in order to save time, which is far too few. The re-run uses three forks with three warmup and five measurement iterations.

On #11494, thanks for the pointer. I have only read its description and file list so far rather than the diff, so please treat this as provisional. From those, it looks like it targets a different phase: it reduces memory during file-based IMap WAL recovery, which runs when state is rebuilt from disk, whereas the cost here is on the runtime read path serving a single HTTP request. Both follow from retained history growing, but I do not think one substitutes for the other. Do you see a connection I am missing? I am happy to read it properly and test locally if you think it bears on this.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for addressing the pagination validation and documenting the compatibility impact.

I checked the current Web UI, and no UI change is required: it always sends a positive page number and selects the page size from 10, 20, 50, 100, or 500.

There is only one small documentation omission: the Web UI calls GET /running-jobs/summary, which is registered to the same RunningJobsServlet as GET /running-jobs and therefore receives the same new validation. Please include /running-jobs/summary in incompatible-changes.md as an affected endpoint.

No other compatibility issue found.

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@nzw921rx The re-run is done, at the module's BenchmarkBase defaults with -prof gc. Fifteen measurements per point rather than three.

Retained jobs Before After Ratio
1,000 905,705 ± 50,938 us/op 24,218 ± 1,004 us/op 37.4x
10,000 9,233,153 ± 673,522 us/op 157,430 ± 16,030 us/op 58.6x

Relative error is now between 4.1% and 10.2%, against 15% to 43% before. The point estimates barely moved, 36.8x became 37.4x and 58.9x became 58.6x, so the earlier figures were right but poorly evidenced.

The allocation data is the part that answers your question about what is being traded away:

Retained jobs Before After Reduction
1,000 1,172 MB/op 29.9 MB/op 39.1x
10,000 12,761 MB/op 211 MB/op 60.3x

At ten thousand retained jobs, GC time over the trial fell from 2,644 ms to 468 ms and collections from 144 to 80.

So at that size the old path allocated roughly 12.7 GB in order to return ten rows. That is the answer to what was sacrificed, which is nothing: the allocation reduction of 60.3x tracks the timing reduction of 58.6x almost exactly, which is what you would expect if the change simply stops building rows that were discarded immediately afterwards. It is not a trade of one cost against another.

To be clear on scope, this closes the GC part of what you asked about. I still have not run a flame graph or JFR, so that part of the gap remains open. Say the word if you want either and I will do them.

Two caveats on the method, both carried over from my previous comment. The first is that the baseline calls this branch's refactored unpaged method rather than dev's, so it includes one extra list allocation that dev does not have. At roughly 40 KB against 12,761 MB that is immaterial. The second matters more: preloadStoragePressure stores the same JobState instance under every key, so all the metrics lookups hit a single key in one partition, whereas real traffic would spread across distinct keys and partitions.

That second one flatters the old path far more than the new one, since it performs twenty thousand of those lookups against twenty. If lookups became more expensive the old figure would rise sharply while the new one barely moved, because roughly 94% of its remaining cost is the scan. So the absolute times and allocations here are optimistic for both paths, but the ratio is if anything conservative rather than inflated.

Thanks also for catching /running-jobs/summary. That is now named in the incompatibility entry in both languages.

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1 LGTM if CI pass

Thank you for your reply. You have accurately answered my question🚀

I think there may not be a need to add new benchmark PR for this in the future

@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 thorough back-and-forth since my last pass, and thanks especially to @SEZ9 for the detailed seven-point list and to @nzw921rx for pressure-testing the benchmark methodology and catching the /running-jobs/summary documentation gap. I re-pulled the current head (2dd45e26f86, PR description shows 2dd45e26f8613e0ee682d48aed9e963fc1d004f7) into a clean worktree and re-read every changed file end to end, including the whole discussion thread, rather than trusting my two earlier approvals.

What Problem Does This PR Solve?

  • User pain point: GET /finished-jobs/:state?page=&rows= built the entire finished-jobs listing, including a per-job metrics lookup and a per-job DAG lookup for every job matching the state filter, and only sliced the result down to one page afterwards. A UI asking for page 1 of 10 rows out of a history of thousands of finished jobs still paid thousands of IMap point-lookups and metric aggregations just to discard almost all of them.
  • Fix approach: filter and sort the finished-job listing into a lightweight List<JobState> first (matchingJobStates), slice the page from that list, and only then run the per-job metrics/DAG lookups (toJobInfoJson) for the rows actually returned. Since my last review, the pagination-parameter handling itself was also hardened in response to @SEZ9's review: rows is now validated the same way page is, the start-offset multiplication is computed in long arithmetic and rejects overflow, the pre-existing writeJsonWithPagination path (used by /running-jobs and /running-jobs/summary) is routed through the same pageParams()/checkPageInRange() helpers instead of duplicating the parsing logic, the new service overload has explicit precondition checks, and both the REST docs and incompatible-changes.md (English and Chinese) now name all three affected endpoints.
  • One-sentence summary: a well-scoped, now thoroughly reviewed performance fix with a genuinely proving regression test (asserts lookup count, not just output shape) and a complete, symmetric pagination-validation hardening pass.

One Simple Concrete Example

10,000 retained finished jobs, client requests GET /finished-jobs/FINISHED?page=1&rows=10.

  • Before: getJobsByStateJson(state) builds all 10,000 rows (two IMap point lookups + a metrics aggregation each), PageBaseServlet#writeJsonWithPagination then keeps only 10 and discards 9,990. Benchmarked at ~9.2s / ~12.7GB allocated per call.
  • After: matchingJobStates filters/sorts 10,000 lightweight JobState entries (unchanged cost), .skip(0).limit(10) selects 10, and only those 10 pay the point lookups. Benchmarked at ~0.157s / ~211MB per call (37–59x faster depending on retention size, evidenced twice with tightened confidence intervals after @nzw921rx pushed on methodology).

Real SeaTunnel Runtime Flow

Web UI (polls every 5s) / CLI
    -> HTTP GET /finished-jobs/:state?page=&rows=
    -> JettyService routes to FinishedJobsServlet (shared instance, extends PageBaseServlet)
    -> FinishedJobsServlet#doGet
         -> PageBaseServlet#pageParams(req)          [parses+validates page/rows, computes start]
         -> JobInfoService#getJobsByStateJson(state, start, rows)
              -> matchingJobStates(state)             [IMap read: IMAP_FINISHED_JOB_STATE, filter+sort, collect to List]
              -> matches.stream().skip(start).limit(rows).map(toJobInfoJson)
                   -> getFinishedJobMetricsJson       [IMap point lookup: IMAP_FINISHED_JOB_METRICS]
                   -> getFinishedJobDAGInfo           [IMap point lookup: IMAP_FINISHED_JOB_VERTEX_INFO]
         -> PageBaseServlet#checkPageInRange(pageParams, jobPage.getTotal())
         -> PageBaseServlet#writeJsonPage             [{"data": [...], "total": n}]

This is the normal request path, not a recovery/exception/race path — every paginated finished-jobs query goes through the reordered code.

1. Code Change Review

1.1 Core Logic Analysis

JobInfoService.java:119-207 (line numbers per current head): the filter predicate (state match, non-null) and the sort comparator (finishTime, nulls-last, reverse order = newest first) are byte-for-byte unchanged from the original single-method implementation, just factored into matchingJobStates, and both the new paged overload and the refactored no-arg overload now share it plus the extracted toJobInfoJson helper. I traced the two call sites and confirmed both produce identical JSON content and ordering to the pre-existing code for any given snapshot of the underlying IMaps.

PageBaseServlet.java: pageParams() is now the single definition of pagination-input parsing for the whole class hierarchy. writeJsonWithPagination (used by RunningJobsServlet for both /running-jobs and /running-jobs/summary, since both are registered against the same servlet instance in JettyService.java:237-238) and FinishedJobsServlet both route through it, positiveIntParam, and checkPageInRange, closing @SEZ9's item 3 (duplication) for real rather than superficially.

Overflow handling (@SEZ9 item 1): long start = (long) (page - 1) * rows; with page and rows both already validated >= 1 via positiveIntParam, so the multiplication itself cannot overflow long; the result is then checked against Integer.MAX_VALUE before narrowing. I verified this against the new shouldRejectOffsetThatOverflowsAnInt test (page=Integer.MAX_VALUE, rows=10) and by hand-tracing the arithmetic — it correctly rejects rather than wrapping.

Boundary semantics (@SEZ9 item 2): checkPageInRange still uses start > total, so a page starting exactly at total returns an empty page. I confirmed this against the pre-existing writeJsonWithPagination logic on dev (start > total || page < 1) — the boundary is identical, so this is a correctly preserved behavior, not a regression, and it's now recorded in a code comment explaining why it's deliberate.

Preconditions (@SEZ9 item 4): getJobsByStateJson(state, start, rows) now explicitly rejects state == null, start < 0, and rows < 1 with messages naming the argument, before any Stream code runs.

One thing worth double-checking on a future pass rather than blocking on now: writeJsonWithPagination's Math.min(start + pageParams.getRows(), total) still adds two ints without the same overflow guard used for the multiplication in pageParams(). I could not construct a realistic input that reaches it, because checkPageInRange rejects start > total first, and total (the real count of running/finished jobs) would have to be within a few rows of Integer.MAX_VALUE for the addition itself to wrap — not achievable by any real cluster's job count. This is pre-existing (the same shape of addition existed on dev before this PR) and not something this PR needs to fix, but see Issue 1 below for the sake of a complete boundary review.

1.2 Compatibility Impact

Partially incompatible — narrow and fully documented. rows=0, which previously returned an empty page, and negative rows, which previously produced an internal error, both now return 400 with a message naming the parameter. Every other input that was valid before (positive page/rows, a page landing exactly at total) behaves identically, and the response envelope ({"data": [...], "total": n} vs. the bare array when no page param is sent) is unchanged. The incompatibility is recorded in incompatible-changes.md in both languages and correctly names all three affected endpoints (/finished-jobs/:state, /running-jobs, /running-jobs/summary) — I independently verified in JettyService.java that /running-jobs and /running-jobs/summary are registered against the same RunningJobsServlet instance, so @nzw921rx's catch was correct and the fix is complete, not partial.

1.3 Performance / Side-Effect Analysis

No new locks, threads, retries, or unbounded structures introduced. The per-request cost for a paged request drops from O(matches) to O(page size) for the metrics/DAG point lookups; the upstream scan+sort in matchingJobStates is unchanged (explicitly called out as a known, documented, unaddressed cost in both the PR description and the resolution of @SEZ9's item 7). For an out-of-range page (start > total), the new code does strictly less work than before it rejects the request, since skip(start) on a list-backed stream past its end produces zero elements and therefore zero per-row lookups before checkPageInRange throws — the old code would have built the entire array first. No resource-release concerns; nothing here opens closables.

1.4 Error Handling and Logging

IllegalArgumentException from the new validation is caught by the existing ExceptionHandlingFilter and turned into an HTTP 400 (RestHttpGetCommandProcessor.java:179, ExceptionHandlingFilter.java:52), consistent with the rest of the codebase's error-handling convention. No exceptions are swallowed. No sensitive data is logged. See Issue 1 for a minor message-clarity nit.

2. Code Quality Assessment

2.1 Coding Standards

Clean, matches surrounding style. JobInfoService.JobPage's constructor is public rather than package-private, which the PR description flags proactively as "not asked for" — I agree this is reasonable given it's an immutable value type newly introduced by this PR (not a previously-released type), so widening it carries no compatibility cost.

2.2 Test Coverage and Test Stability

JobInfoServiceNullSafetyTest#shouldApplyPageBeforePerJobLookups asserts on lookup count (verify(finishedJobMetricsMap, times(10))...) rather than only on output shape — exactly the right invariant to prove the perf claim, since a bug that built the whole list and sliced afterwards would still pass an output-only assertion. shouldReturnNewestFinishedJobsFirst locks down sort order. The new FinishedJobsServletTest (9 cases) closes @SEZ9's item 6: zero/negative rows, non-integer input, non-positive page, int-overflow offset, page-exactly-at-total, page-beyond-total, and routing between the paged/unpaged service calls, all against a mocked JobInfoService via the newly test-visible package-private constructor. All tests are Mockito-based, synchronous, no Thread.sleep, no timing dependencies, no shared mutable state between tests. Stability rating: Stable.

One minor gap, not blocking: there's no dedicated RunningJobsServletTest exercising the shared pageParams/checkPageInRange path through RunningJobsServlet directly; coverage there is indirect, via FinishedJobsServletTest exercising the same protected base-class methods through the sibling subclass. Given both subclasses call the identical shared code, this is a low-risk gap rather than a functional one.

I confirmed in the fork's actual CI run (awsomesud347/seatunnel run 34089819303, since the apache/seatunnel "Build" check is only a pointer to it) that all unit-test jobs (JDK 8/11, ubuntu/windows) passed, so these tests do run and pass in CI, not just locally.

2.3 Documentation Updates

docs/en/engines/zeta/rest-api-v2.md and docs/zh/engines/zeta/rest-api-v2.md both updated with matching content: parameter constraints, the pagination envelope, and the 400 conditions. docs/en/introduction/concepts/incompatible-changes.md and the zh equivalent both carry a complete, accurate entry under ## dev naming all three affected endpoints. I checked both language versions for parity — they say the same thing. Current and usable.

3. Architectural Soundness

3.1 Layering: the split between matchingJobStates (scan/filter/sort) and toJobInfoJson (per-row enrichment) cleanly separates the part of the cost that scales with retention from the part that scales with page size, matching the PR's own stated boundary (pagination cannot speed up the scan, and it doesn't claim to).

3.2 Blast radius: changes are confined to seatunnel-engine-server's REST pagination layer (PageBaseServlet, JobInfoService, FinishedJobsServlet) plus docs and tests. No connector, SPI, mapper, or dist/packaging surface is touched, so the usual connector-registration audit does not apply here.

3.3 Concurrency: I looked specifically for the possibility that moving lookups after slicing could change which jobs get counted under concurrent job completion (this was flagged to me as a specific thing to check). It doesn't: matchingJobStates collects the filtered/sorted list into a fixed List in one pass per request (Collectors.toList()), so both total and the page slice are computed from the same snapshot, exactly as the old code's single stream pipeline was. Offset-based pagination's inherent susceptibility to drift between two separate requests (a job finishing between a page-1 and page-2 call) is unchanged by this PR — it was already present in the pre-existing implementation, since that also re-scanned the IMap fresh on every request. No new race window is introduced.

3.4 Extensibility: pageParams()/checkPageInRange()/writeJsonPage() being protected on PageBaseServlet gives any future paginated endpoint the same validated behavior for free, which is the right shape for this kind of shared concern.

4. Issue Summary

Number Issue Location Severity
1 writeJsonWithPagination's start + pageParams.getRows() addition is not overflow-guarded the same way the pageParams() multiplication is; unreachable in practice because checkPageInRange rejects start > total first and total cannot realistically approach Integer.MAX_VALUE, but inconsistent with the new overflow-hardening elsewhere for defense in depth PageBaseServlet.java (writeJsonWithPagination, the subList line) Low
2 The overflow-rejection message in pageParams() and the out-of-range message in checkPageInRange() are textually identical ("Page number exceeds total pages"), which can make it harder to tell from the client side which condition actually triggered PageBaseServlet.java (pageParams(), checkPageInRange()) Low
3 No dedicated RunningJobsServletTest directly exercises the shared pagination-validation path through /running-jobs//running-jobs/summary; coverage is indirect via the sibling FinishedJobsServletTest seatunnel-engine-server test sources Low

No Medium or High severity issues found in this pass. All seven items from @SEZ9's review are resolved (five by code change, one — the start/total boundary — confirmed as an intentional, now-documented preservation of legacy behavior, one — matchingJobStates cost — accepted as a follow-up and recorded in the PR description as requested).

5. Merge Recommendation

Conclusion: Ready to merge.

Blockers: none.

Recommended fixes (non-blocking, optional follow-up): address Issues 1–3 above if convenient, but none of them represent a functional regression or a reachable production risk given the current constraints on total.

Overall assessment: this went through a genuinely productive multi-reviewer pass — @SEZ9's seven-point list and @nzw921rx's benchmark-methodology pressure-testing and documentation catch materially improved the PR beyond what either of my first two approvals covered, and the author addressed every item with either a real code change or a clearly reasoned "intentional, here's why." My own independent re-trace of the runtime path, the concurrency/snapshot question, and the pagination arithmetic did not turn up anything beyond the three Low-severity nitpicks above. CI's two failing jobs on the fork (PaimonWithS3IT timeouts referencing the known #11679 pattern, and AzureCosmosDBSourceIT's emulator startUp failure) are both in unrelated connector E2E modules with no code-path connection to seatunnel-engine-server's REST layer, and every unit-test job (which covers the new tests) passed. +1 to merge once CI is green on a rerun of those two unrelated jobs.

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@SEZ9 All seven are addressed as of 2dd45e26f, in your numbering.

  1. pageParams() now validates both parameters rather than only page. A value that is not an integer produces a message naming the parameter instead of the JDK's wording, and a value below 1 is rejected for both page and rows. The start offset is computed as (long) (page - 1) * rows and rejected if it exceeds Integer.MAX_VALUE before being narrowed, so the wrap you described can no longer reach checkPageInRange. The validated offset is stored on PageParams rather than recomputed on demand, so no accessor can throw.

  2. No change, and it is intentional. The legacy method used start > total || page < 1, so a page starting exactly at total has always returned an empty page rather than being rejected, and checkPageInRange preserves that exactly. There is now a comment recording it so a later reader does not "fix" it. If you would rather it rejected, that is a one line change.

  3. Done. writeJsonWithPagination now calls pageParams(), checkPageInRange() and writeJsonPage(), so there is a single definition of pagination input handling. This means /running-jobs and /running-jobs/summary pick up the same validation, so rows=0 there now returns 400 where it previously returned an empty page.

  4. Done. getJobsByStateJson(state, start, rows) now rejects a null state, a negative start and a rows below 1, each with a message naming the argument, rather than relying on the stream pipeline to fail.

  5. Done. The page and rows tables in docs/en/engines/zeta/rest-api-v2.md and docs/zh/engines/zeta/rest-api-v2.md now state the constraints and the 400 behaviour, and describe both the envelope and the out of range semantics. There is also an entry in incompatible-changes.md in both languages. Following @nzw921rx's review that entry names /running-jobs/summary as well, since it is registered against the same RunningJobsServlet instance and therefore receives the same validation.

  6. Done. A new FinishedJobsServletTest adds nine tests covering zero and negative rows, a non integer value, a page below 1, an offset that overflows an int, a page starting beyond the end of the results, a page starting exactly at total, and the routing between the paged and unpaged service calls.

    One thing to flag since you did not ask for it. Making the servlet testable required a package private FinishedJobsServlet(NodeEngineImpl, JobInfoService) constructor, following the existing WorkerResourceServlet pattern, and widening JobInfoService.JobPage's constructor from private to public, because JobPage is a final class that Mockito cannot stub. Happy to take a different approach if you would rather it stayed private.

  7. Done, in the description, which now records that matchingJobStates() still fetches, deserialises and sorts every retained JobState on each request and that only the per row work became lazy.

@DanielLeens thanks for the re-read. On your three findings: Issue 2 is a fair hit and mine, both the overflow rejection and the out of range check throw the identical string "Page number exceeds total pages" (PageBaseServlet lines 121 and 150), so a client cannot tell which fired. Issue 1 I agree is unreachable, since checkPageInRange rejects start > total before the addition and total is a job count. Issue 3 is fair too. I have left all three rather than spend a full CI cycle on them, but say the word and I will fix Issue 2 in particular.

On CI. There are no test failures against this change anywhere. Across four attempts every job has passed at least once: Azure Cosmos DB and Paimon cleared on the second, RocketMQ on the third. The run still reports cancelled because kudu-connector-it (11) has now hit its 90 minute limit (backend.yml:1514) twice in a row, while the same tests pass on JDK 8 in 27 minutes. It has never actually failed a test. I have stopped retrying rather than keep rolling the same dice.

@nzw921rx flagging that for you since your approval was conditional on CI passing. The diff is confined to PageBaseServlet, JobInfoService and FinishedJobsServlet, and no E2E test in the repository references /finished-jobs or /running-jobs, so nothing in the connector suites has a code path to this change. Happy to rerun again if you would rather see a fully green run.

Locally, mvnw test -pl seatunnel-engine/seatunnel-engine-server passes with 470 tests, no failures and no errors, and spotless:apply and mvnw -DskipTests verify are clean.

@SEZ9

SEZ9 commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator

@DanielLeens thanks for re-pulling 2dd45e26f86 (2dd45e26f8613e0ee682d48aed9e963fc1d004f7) into a clean worktree and re-reading the changed files end to end.

Your problem/fix summary matches my reading: the old GET /finished-jobs/:state?page=&rows= path paid per-job metrics and DAG lookups for every job matching the state filter before slicing, and the new flow filters/sorts into a lightweight List<JobState> via matchingJobStates, slices the page, and only then runs the per-row lookups.

Your comment appears to have been cut off after the "Fix approach" bullet. If there was a verdict or a question at the end, please re-post it so I do not have to guess.

From my earlier review, here is what I still need confirmed at the current head:

  1. pageParams() should validate rows the same way it validates page, and PageParams.getStart() should guard the multiplication so overflow cannot wrap to a small positive value and slip past checkPageInRange. Today invalid input can surface as an opaque JDK exception or silently serve the wrong page.
  2. checkPageInRange uses start > total; please confirm whether a page starting exactly at total should be an empty page or a rejection, and that this matches the legacy writeJsonWithPagination() behavior used by the other paged servlets.
  3. pageParams()/checkPageInRange() and writeJsonWithPagination() now duplicate parse/validate logic — either fold them together or note why they must stay separate.
  4. getJobsByStateJson(state, start, rows) should have explicit precondition checks rather than relying on Stream internals to reject bad arguments.
  5. REST API documentation and a release-note entry for the changed pagination semantics of GET /finished-jobs/:state.
  6. Test coverage for the servlet-side surface (pageParams, checkPageInRange, writeJsonPage, and the FinishedJobsServlet wiring); JobInfoServiceNullSafetyTest currently only exercises the service overload.
  7. A note in the PR description that matchingJobStates() still deserializes and sorts every retained JobState per request, so the remaining cost is not misread as fixed — fine as a follow-up.

If any of these are already addressed in 2dd45e26f86, a short pointer to where is all I need and I will re-check.

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@SEZ9 I posted a per-item response about 25 minutes before your comment, so you may not have seen it: #12130 (comment)

All seven are addressed at 2dd45e26f. Pointers, in your numbering:

  1. PageBaseServlet.pageParams() plus the new positiveIntParam() helper. rows is validated like page, the offset is computed in long and rejected above Integer.MAX_VALUE before narrowing, and parse failures name the parameter.
  2. PageBaseServlet.checkPageInRange(). Empty page, deliberately, and it matches the legacy writeJsonWithPagination condition (start > total || page < 1) byte for byte. There is a comment on the method recording why.
  3. PageBaseServlet.writeJsonWithPagination() now routes through pageParams(), checkPageInRange() and writeJsonPage(), so the duplication is gone rather than documented.
  4. JobInfoService.getJobsByStateJson(state, start, rows), explicit checks for null state, negative start and rows below 1.
  5. docs/en/engines/zeta/rest-api-v2.md and the zh equivalent, plus an incompatible-changes.md entry in both languages naming all three affected endpoints.
  6. New FinishedJobsServletTest, nine tests covering the servlet surface and the wiring.
  7. In the PR description.

Also, DanielLeens's review is not truncated, GitHub just collapses long comments behind a "show more" control. His verdict at the end is "Ready to merge, blockers: none," with three Low severity nits.

@DanielLeens

Copy link
Copy Markdown
Contributor

@SEZ9 @awsomesud347 Confirming I've re-checked the current head (2dd45e26f8613e0ee682d48aed9e963fc1d004f7) and it's exactly the commit my last review covered — nothing has moved since that approval.

@SEZ9, I think our comments crossed: the checklist you re-posted is the same one from my second-round review, and my third pass (the one ending "Ready to merge, blockers: none") already confirms all seven items resolved at 2dd45e26f — five by code change, the start == total boundary kept intentionally (matches legacy writeJsonWithPagination behavior, now documented), and the matchingJobStates cost recorded as a follow-up in the PR description. GitHub just collapses that review body behind "show more," which is presumably why it read as cut off. Good to hear your independent re-trace of the problem/fix matches mine — appreciate you double-checking the diff rather than taking my word for it.

The one thing still open is a real green Build run: it's currently showing cancelled from kudu-connector-it hitting the 90-minute job budget twice, which per @awsomesud347's account is a timeout rather than a test failure, and unrelated to this diff (PageBaseServlet/JobInfoService/FinishedJobsServlet, no Kudu code path touched). That matches the same "unrelated connector E2E timeout" pattern as the Paimon/Cosmos DB flakes from the prior run. My approval stands, conditioned on getting that rerun clean the way I noted before — no further code changes needed on my end.

Thanks both for the thorough back-and-forth here — this is a good example of review actually sharpening a PR rather than just rubber-stamping it.

@SEZ9

SEZ9 commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

@DanielLeens thanks for confirming the head is still 2dd45e26f8613e0ee682d48aed9e963fc1d004f7 and matches the commit your last review covered.

Your comment lays out how each of the earlier review points was handled: most by code change, the start == total boundary in checkPageInRange kept intentionally for parity with the legacy writeJsonWithPagination behavior and documented, and the matchingJobStates() materialize/sort cost recorded as a follow-up in the PR description. I don't want to mark those resolved from the description alone, so could you point me at the specific hunks, the doc text covering the boundary behavior, and the follow-up note in the PR description? With those in hand I can close out the checklist against 2dd45e26f.

On CI: I understand from your account that the kudu-connector-it cancellations are timeouts rather than test failures and that this diff doesn't touch a Kudu code path. I'd still like to see one clean Build run on 2dd45e26f before this merges.

No further code changes requested from my side. Appreciate the careful back-and-forth.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEZ9 — fair ask, a summary conclusion isn't the same as a pointer you can verify yourself. I re-pulled 2dd45e26f8613e0ee682d48aed9e963fc1d004f7 again and confirmed each of these against the actual current file contents (not my notes):

  1. rows validation + overflow guard — PageBaseServlet.java:107-124 (pageParams()): rows goes through the same positiveIntParam() helper as page (:112-114), and the offset is computed as long start = (long) (page - 1) * rows; with an explicit start > Integer.MAX_VALUE rejection (:119-122) before narrowing to int. positiveIntParam() itself is :126-139.
  2. start == total boundary, kept intentional — PageBaseServlet.java:141-152 (checkPageInRange()), with a doc comment on the method (:142-146) explicitly recording that a page starting exactly at total returns an empty page rather than being rejected, and why (matches legacy writeJsonWithPagination behavior).
  3. Duplication folded together — PageBaseServlet.java:48-70 (writeJsonWithPagination()): it now calls pageParams(req) (:53), checkPageInRange(pageParams, total) (:58), and writeJsonPage(...) (:69) instead of having its own parse/validate logic. This is the same method RunningJobsServlet calls for /running-jobs and /running-jobs/summary, so both endpoints now go through the identical validation path.
  4. JobInfoService preconditions — JobInfoService.java:135-146 (getJobsByStateJson(String state, int start, int rows)): explicit state == null, start < 0, rows < 1 checks, each with a message naming the argument, before matchingJobStates(state) runs.
  5. Docs — docs/en/engines/zeta/rest-api-v2.md:786-795 states the page/rows constraints and the three 400 conditions (non-integer, non-positive, out-of-range) plus the start == total empty-page carve-out; docs/zh/engines/zeta/rest-api-v2.md carries the same in Chinese. docs/en/introduction/concepts/incompatible-changes.md:6-12 (and the zh equivalent) has a ## dev entry naming all three affected endpoints, GET /finished-jobs/:state, GET /running-jobs, and GET /running-jobs/summary — I checked JettyService.java again and confirmed the latter two really do share RunningJobsServlet, so item 3 above is what makes this entry accurate rather than aspirational.
  6. Servlet-level tests — new file seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/servlet/FinishedJobsServletTest.java, plus the package-private FinishedJobsServlet(NodeEngineImpl, JobInfoService) constructor at FinishedJobsServlet.java:41-44 that makes it testable without a running node engine.
  7. matchingJobStates() cost documented as a follow-up — PR description, the paragraph beginning "One cost this PR does not remove, for the record." It's not in a source comment, just the description; say the word if you'd rather it also live as a code comment on JobInfoService.matchingJobStates() (:164) so it survives a squash-merge losing the description.

On CI: no change since my last comment. I re-checked the fork directly (awsomesud347/seatunnel run 34089819303) rather than trusting the apache-side pointer — it's still cancelled, attempt 4, same as when I last looked, with no newer run triggered. So we're still waiting on the kudu-connector-it 90-minute-budget issue the author described to actually get resolved with a clean run; nothing here changes my "approval stands, conditioned on a clean Build" position from before.

@DanielLeens

Copy link
Copy Markdown
Contributor

Follow-up on the CI side, since a clean Build run is the only thing still open here. I pulled the job logs rather than going by the run summary.

What is actually red. On fork run awsomesud347/seatunnel 34089819303 the only job that never went green across attempts 1-4 is kudu-connector-it (11), cancelled at the 90-minute job limit every time. The three jobs that failed in attempt 1 (all-connectors-it-4 (11), paimon-connector-it (8), rocketmq-connector-it (8)) all passed on re-run with no code change, and kudu-connector-it (8) passed in attempt 1 in 27 minutes.

  • attempt 1, job 101641543194: KuduIT#testKuduMultipleReadWithRegex on the Flink 1.15.3 leg. The TaskManager logs The heartbeat of JobManager ... timed out at 06:48:06, then Could not resolve JobManager address ... every 10 s until it exits at 06:53:21 with RegistrationTimeoutException; after that the log is silent for 71 minutes because the test JVM is still inside container.executeJob.
  • attempt 4, job 101844792732: KuduIT#testKuduMultipleRead on the Flink 1.18.0 leg. The JobMaster logs Deploying Source: Kudu-Source -> MultiTableSink-Sink: Writer (1/1) (attempt #0) at 19:39:48 and never logs again. The TaskManager logs BlobClient - Downloading .../p-... from jobmanager at 19:39:48, Slot offering to JobManager did not finish in time at 19:39:58 and The heartbeat of JobManager ... timed out at 19:41:48. From there until the cancel at 20:47 the ResourceManager/TaskManager slot-allocation loop just repeats (446 DefaultSlotStatusSyncer and 753 DefaultJobLeaderService lines) and flink run never returns.

That is the signature tracked in #12132: the JobMaster stops answering at the first task deployment of the first job on a freshly started JobManager/TaskManager pair, on the 1.15.3 and 1.18.0 legs in PR runs (and on the 1.16.0 and 1.17.2 legs in the scheduled full matrix), never so far on 1.13.6 or 1.20.1, and AbstractTestFlinkContainer.executeJob has no upper bound, so the job burns the whole budget. It is not specific to this branch, this commit or JDK 11:

Nothing in this diff can reach that path: the change is confined to PageBaseServlet, JobInfoService and FinishedJobsServlet in seatunnel-engine-server, and none of connector-kudu, seatunnel-e2e-common, connector-kudu-e2e or the Flink starters declare a dependency on that module; the Flink e2e containers only get the Flink starter and the connector jars.

Two things to move this along:

  1. @awsomesud347 only the fork owner can re-run a job on your fork. Could you re-run just the failed job on run 34089819303 (Actions, open the run, "Re-run failed jobs") rather than pushing a new commit? That costs one Kudu leg instead of the whole matrix, and the sibling leg consistently finishes in about 27 minutes.
  2. In parallel I pushed the identical commit 2dd45e26f8613e0ee682d48aed9e963fc1d004f7 to my fork so the full Build workflow runs the same SHA once more under a fork where I can re-run individual jobs: https://github.com/DanielLeens/seatunnel/actions/runs/34377408910. Same commit, same tree, so a green result there is a direct check of this head. I will link the outcome here once it completes.

@SEZ9 the above is the evidence behind "cancelled, not failed" on 2dd45e26f. Making the hang fail fast instead of eating 90 minutes is the #12132 fix (a bounded wait in executeJob plus a JobManager thread dump when the job never reaches RUNNING) and belongs in its own PR, not here.

@awsomesud347

Copy link
Copy Markdown
Contributor Author

CI is now green on 2dd45e26f. Run 34089819303 completed on attempt 5 with 80 jobs passing and 13 skipped, and nothing failed or was cancelled. The Build check on the apache side has gone green as well.

@DanielLeens this was the targeted rerun of the failed job that you suggested, rather than a new commit, so the tree is unchanged and this is the same 2dd45e26f8613e0ee682d48aed9e963fc1d004f7 that you re-pulled into a clean worktree. Your diagnosis holds up from this side too, because kudu-connector-it (11) completed in 25 minutes this time against the JDK 8 leg's 27, which means that when it avoids the #12132 hang it finishes comfortably inside the 90 minute budget. Thank you for tracing the evidence across the other pull requests, and particularly for finding that apache's own scheduled dev run lost both Kudu legs in the same way, since that is a far better answer than treating it as ordinary flakiness.

@SEZ9 this clears the clean Build run on this commit that you were waiting on before merge.

@nzw921rx
nzw921rx requested a review from davidzollo September 10, 2026 02:24
@DanielLeens

Copy link
Copy Markdown
Contributor

Confirmed — I just re-pulled the current state directly rather than going by this thread: Build on 2dd45e26f is SUCCESS on the apache side, and I checked run 34089819303 on the fork directly as well — attempt 5, 80 jobs passed, 13 skipped, nothing failed or cancelled. kudu-connector-it (11) finished in 25 minutes this run, consistent with my diagnosis that the earlier cancellations were the #12132 Flink-container hang eating the 90-minute budget, not a real failure in this diff.

That was the one condition my approval was standing on, so with a clean Build on the exact commit I reviewed (2dd45e26f8613e0ee682d48aed9e963fc1d004f7, unchanged since my last pass), my APPROVED review holds unconditionally now — no further action needed from me. Since I'm comment-only, this still needs a write-capable maintainer to do the actual merge, but from a review standpoint this is ready to go.

Thanks both for chasing the CI signal down to the actual job logs instead of treating it as generic flakiness — that made this a much cleaner call than it would otherwise have been.

@SEZ9

SEZ9 commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator

Thanks @awsomesud347 for the targeted rerun and @DanielLeens for verifying run 34089819303 and the Build result on 2dd45e26f directly — good to have a clean Build on the exact reviewed commit (2dd45e26f8613e0ee682d48aed9e963fc1d004f7), and tracing kudu-connector-it (11) to the job logs rather than writing it off as flakiness was the right call.

Since the recent comments only cover CI, I'd like to re-check the points from my earlier review against this commit before we merge. I may well have missed changes, so please point me at anything already addressed:

  • F1 / F5 (pageParams() / PageParams.getStart()): is rows validated alongside page, and is the start computation protected against int overflow (which could either surface an opaque JDK exception or wrap to a small positive value that slips past checkPageInRange)?
  • F2 (checkPageInRange): with start > total, a page starting exactly at total returns an empty page rather than being rejected — does that match the legacy writeJsonWithPagination behavior?
  • F4: pagination parsing/validation appears duplicated between pageParams()/checkPageInRange() and writeJsonWithPagination(); could the paged servlets share one path, or at least the validation?
  • F6 (getJobsByStateJson(state, start, rows)): are there explicit precondition checks, or does argument validation still fall through to Stream internals?
  • F3 (FinishedJobsServlet): the GET /finished-jobs/:state pagination semantics change (source-side slicing, out-of-range behavior) — is there a REST API documentation update for this?
  • F7 (tests): JobInfoServiceNullSafetyTest exercises the service overload; is the servlet path (pageParams, checkPageInRange, writeJsonPage, FinishedJobsServlet wiring) covered by existing REST API IT/E2E tests, or would a targeted test be worth adding?
  • F8 (matchingJobStates()): LOW — happy to track this as a follow-up if you'd prefer.

None of these are meant to reopen the CI discussion; I just want to confirm their status on this commit so we merge with a clear picture.

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@SEZ9 All eight are already addressed on this commit. They were answered per item in #12130 (comment), with locations in #12130 (comment), and @DanielLeens independently verified them against the file contents in #12130 (comment). Here they are once more against your F numbering, with line numbers on 2dd45e26f so you can check each one directly.

F1 and F5, PageBaseServlet.java:107-124. rows goes through the same positiveIntParam() helper as page at :112-114, so both are rejected when non-integer or below 1. The offset is computed as long start = (long) (page - 1) * rows at :119 and rejected at :120-122 if it exceeds Integer.MAX_VALUE, before it is narrowed to int. PageParams.getStart() at :91-93 returns a value validated at construction, so it cannot throw and cannot wrap. positiveIntParam() itself is at :126-139 and names the offending parameter rather than surfacing the JDK message.

F2, PageBaseServlet.java:148-152. It uses start > total, which is exactly the legacy writeJsonWithPagination condition (start > total || page < 1), so a page starting precisely at total returns an empty page just as it always has. The javadoc at :141-147 records that this is deliberate.

F4, PageBaseServlet.java:48-70. writeJsonWithPagination() no longer parses or validates anything itself. It calls pageParams(req) at :53, checkPageInRange(...) at :58 and writeJsonPage(...) at :69. Since RunningJobsServlet uses that method for both /running-jobs and /running-jobs/summary, all three paginated endpoints now share one validation path.

F6, JobInfoService.java:135-146. Explicit checks for a null state, a negative start and a rows below 1, each with a message naming the argument, before any stream code runs.

F3, docs/en/engines/zeta/rest-api-v2.md:786-795 states the constraints, the 400 conditions and the empty-page carve-out, with the same content in Chinese at docs/zh/engines/zeta/rest-api-v2.md:759-765. There is also a ## dev entry in docs/en/introduction/concepts/incompatible-changes.md:8 and its Chinese equivalent, naming all three affected endpoints.

F7, new file FinishedJobsServletTest, nine tests covering zero and negative rows, non-integer input, a page below 1, an offset that overflows an int, a page beyond the end, a page exactly at total, and the routing between the paged and unpaged service calls. It uses a package-private FinishedJobsServlet(NodeEngineImpl, JobInfoService) constructor added for that purpose.

F8, agreed as a follow-up, and recorded in the PR description in the paragraph beginning "One cost this PR does not remove, for the record."

Two of the F items describe the code before fad034342 rather than the current head, which may be why they read as outstanding. F1's concern about an overflow wrapping past checkPageInRange is what :119-122 now prevents, and the duplication in F4 was removed when writeJsonWithPagination was routed through the shared helpers.

@DanielLeens

Copy link
Copy Markdown
Contributor

@SEZ9 @awsomesud347 Confirming from my side too. These pointers match what I already independently verified against the actual file contents on this same commit (see #12130 (comment) for F1-F7), and F8 was already recorded as a follow-up in the PR description rather than something this PR needs to fix. Nothing has moved since my last pass.

With Build green on 2dd45e2, my APPROVED review stands unconditionally. This is ready to merge from a review standpoint. Since I'm comment-only, it will need a write-capable maintainer to actually perform the merge.

@SEZ9

SEZ9 commented Sep 11, 2026

Copy link
Copy Markdown
Collaborator

@awsomesud347 Thanks for laying this out against the F numbering, and apologies for the delay in getting back to you.

On F1 / F5: the approach you describe — rows going through the same positiveIntParam() helper as page, the offset computed as long and rejected when it exceeds Integer.MAX_VALUE before narrowing, and PageParams.getStart() returning a value already validated at construction — is what I was asking for. I'll confirm it against PageBaseServlet.java:107-124 and :126-139 on 2dd45e26f, and based on your description I expect to resolve both.

On F2 and the remaining items: your comment appears to have been cut off mid-sentence, so I can't see the rest of the F2 parity argument or any F3–F8 entries here. I'll go through the per-item answers you linked (5578063614, 5578311990, 5601184777), but if the rest of this comment was meant to add anything beyond those, could you repost it? In particular:

  • F2: confirmation that start > total matches the existing writeJsonWithPagination check rather than tightening or loosening it.
  • F3: where the REST doc / release-note update for the GET /finished-jobs/:state pagination change landed.
  • F4: whether the other paged servlets now share the new helpers, or if the duplication is intentionally left for a follow-up.
  • F6: where the precondition checks on getJobsByStateJson(state, start, rows) live.
  • F7: whether servlet-level tests for pageParams / checkPageInRange / writeJsonPage were added, or if coverage is still only via the service overload.
  • F8: a one-line confirmation that this is tracked as a follow-up is enough.

Once I have that, I'll check each location on 2dd45e26f and close out the review.

@DanielLeens

Copy link
Copy Markdown
Contributor

@SEZ9 Since @awsomesud347's F2-F8 reply looks like it may have been cut off for you the same way mine was earlier in this thread, here's what I can confirm directly against the current head (2dd45e26f) while you wait for a full repost — this overlaps with what I already verified in #12130 (comment), mapped to your numbering:

  • F1/F5 (rows validation + overflow guard) — confirmed, as you expected: PageBaseServlet.java:112-114 runs rows through the same positiveIntParam() helper as page, and :118-122 computes the offset as long and rejects it before narrowing to int if it exceeds Integer.MAX_VALUE.
  • F2 (start > total parity with the old writeJsonWithPagination check) — confirmed, just re-read it myself: checkPageInRange() at PageBaseServlet.java:150-153 throws exactly when pageParams.getStart() > total, and the method's own doc comment (:142-149) records that start == total is deliberately allowed (empty page), matching the legacy behavior. So this is parity, not a tightening or loosening.
  • F3 (docs / incompatible-changes location) — docs/en/engines/zeta/rest-api-v2.md:786-795 (and the zh equivalent) documents the page/rows constraints and the three 400 conditions; docs/en/introduction/concepts/incompatible-changes.md:6-12 (and zh) has a ## dev entry naming all three affected endpoints.
  • F4 (other paged servlets sharing the helpers) — yes, not left as a follow-up: RunningJobsServlet (/running-jobs, /running-jobs/summary) already calls the same writeJsonWithPagination() in PageBaseServlet, so both endpoints go through the identical validation path as /finished-jobs/:state.
  • F6 (preconditions on getJobsByStateJson) — JobInfoService.java:135-146 has explicit state == null / start < 0 / rows < 1 checks, each naming the offending argument, before matchingJobStates(state) runs.
  • F7 (servlet-level tests) — yes: FinishedJobsServletTest.java (new), enabled by the package-private FinishedJobsServlet(NodeEngineImpl, JobInfoService) constructor at FinishedJobsServlet.java:41-44 that makes the servlet testable without a running node engine.
  • F8 (follow-up tracking) — confirmed as a follow-up in the PR description ("One cost this PR does not remove, for the record...") rather than fixed in this PR; not something this PR needs to resolve.

Nothing here has moved since my last pass, and Build is still green on 2dd45e26f. My approval stands unconditionally from a source-review standpoint — happy to have @awsomesud347 repost F2-F8 if there's anything beyond what's listed above, but these pointers should be enough to close out your confirmation pass either way.

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@SEZ9 That comment is complete on GitHub, so your view may be truncating long comments. The short version, on 2dd45e26f:

  • F2 is parity, not a change. checkPageInRange at PageBaseServlet.java:148 uses start > total, the same as the legacy check.
  • F3 is in docs/en/engines/zeta/rest-api-v2.md:786-795 and its zh counterpart, plus incompatible-changes.md in both languages.
  • F4 is shared rather than deferred. writeJsonWithPagination at :48 now calls pageParams, checkPageInRange and writeJsonPage, so RunningJobsServlet uses the same path.
  • F6 is at JobInfoService.java:135-146.
  • F7 is a new FinishedJobsServletTest with nine servlet tests.
  • F8 is tracked in the PR description for a later PR.

@DanielLeens

Copy link
Copy Markdown
Contributor

@awsomesud347 @SEZ9 Confirming I've seen this — nothing new for me to add here since my last pass (still 2dd45e26f8613e0ee682d48aed9e963fc1d004f7, unchanged). The F2/F3/F4/F6/F7/F8 pointers in this short-form recap match exactly what I already independently verified line-by-line against the file contents in my earlier comments, so from a source-review standpoint my APPROVED still stands unconditionally.

@SEZ9, since your open item was a rendering/truncation concern on the longer recap rather than a substantive disagreement, I'll leave the final confirmation pass to you against these pointers — shout if anything still looks unresolved once you've checked them and I'll take another look.

@SEZ9

SEZ9 commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator

@awsomesud347 Thanks — the short version came through fine, and the pointers on 2dd45e26f give me what I need to do a proper pass.

I'll verify F2, F3, F4, F6, F7 and F8 against the actual changes rather than closing them out from the summary alone, in particular:

  • F2: that checkPageInRange uses start > total, matching the legacy check — if so, that's parity rather than a behavior change.
  • F4: that writeJsonWithPagination now delegates to pageParams / checkPageInRange / writeJsonPage so RunningJobsServlet shares the same path.
  • F7: what the new FinishedJobsServletTest covers on the servlet side.
  • F8: tracking it in the PR description for a follow-up is fine with me; not blocking.

One gap in the recap: F1 and F5 (pageParams() not validating rows, and PageParams.getStart() overflowing for large inputs). Could you point me to where rows is validated on 2dd45e26f, how getStart() guards against overflow, and whether FinishedJobsServletTest includes cases for those inputs? With that I can finish the review.

@DanielLeens

Copy link
Copy Markdown
Contributor

@SEZ9 Nothing further needed from me on F2/F3/F4/F6/F7/F8 — your plan to verify those directly against the diff rather than the summary is the right call, and I'd rather you check them yourself too.

On the one gap you flagged, F1/F5, I went back and re-pulled 2dd45e26f8613e0ee682d48aed9e963fc1d004f7 to confirm the exact lines and the test coverage, since that's the one part of your question nobody had answered with specifics yet:

  • PageBaseServlet.java:112-114 — rows goes through the same positiveIntParam() helper as page, so both reject non-integer and non-positive input with a message naming the parameter.
  • PageBaseServlet.java:119-122 — the offset is computed as long start = (long) (page - 1) * rows; and rejected with IllegalArgumentException("Page number exceeds total pages") if it exceeds Integer.MAX_VALUE, before narrowing to int. The comment right above it (:116-118) spells out why: an int overflow here could otherwise wrap to a small positive offset that slips past checkPageInRange.
  • PageBaseServlet.java:91-93 — PageParams.getStart() just returns the value validated at construction, so it can't throw or wrap on its own.

For test coverage specifically, FinishedJobsServletTest.java does cover all three of the inputs you asked about:

  • shouldRejectZeroRows (:127-133) and shouldRejectNegativeRows (:135-141) both assert "Parameter 'rows' must be greater than 0".
  • shouldRejectOffsetThatOverflowsAnInt (:163-169) sends page=Integer.MAX_VALUE, rows=10, asserts "Page number exceeds total pages", and additionally verifies jobInfoService.getJobsByStateJson(...) is never called — so the overflow is caught before it reaches the service layer, not just before it reaches checkPageInRange.

So F1/F5 are covered both in source and in tests on the current head. Nothing here changes my APPROVED — just closing the specific gap you called out.

@awsomesud347

Copy link
Copy Markdown
Contributor Author

@SEZ9 @DanielLeens has it right, and I verified every pointer against 2dd45e26f myself before confirming:

  • F1: rows goes through positiveIntParam at PageBaseServlet.java:113-114, the same helper page uses at :112.
  • F5: getStart() at :91-93 returns a value already validated at construction, and the overflow is caught earlier at :119-122, where the offset is computed as a long and rejected above Integer.MAX_VALUE.
  • Tests: shouldRejectZeroRows at FinishedJobsServletTest.java:127-133, shouldRejectNegativeRows at :135-141, and shouldRejectOffsetThatOverflowsAnInt at :163-169, which sends page=Integer.MAX_VALUE, rows=10 and also asserts the service is never called.

@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! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!

Please ignore the following message if you have joined in the Slack~

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄

@davidzollo
davidzollo added this pull request to the merge queue Sep 14, 2026
Merged via the queue into apache:dev with commit 41a9c4b Sep 14, 2026
3 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.

5 participants