Repository navigation
[Improve][Zeta] Apply the finished-jobs page before the per-job metrics and DAG lookups - #12130
Conversation
…cs and DAG lookups
85ecc58 to
96805de
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
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 AFTERAfter (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-787already documentspage/rowsfor this endpoint; no doc change needed). - Non-paged path (
pageparam absent) returns the same rawJsonArrayas before. totalstill means "count of all state-matching finished jobs," not "count in this page" — same as before.- Page-out-of-range validation (
start > total⇒IllegalArgumentException) andpage < 1validation are preserved, just split betweenpageParams()and the newcheckPageInRange().
Side-Effect Analysis
- Positive: for a paged request, the number of
IMAP_FINISHED_JOB_METRICSandIMAP_FINISHED_JOB_VERTEX_INFOpoint-lookups drops from O(matching jobs) to O(page size) — confirmed by the newshouldApplyPageBeforePerJobLookupstest, which assertsverify(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;
matchingJobStatesstill does a single pass overfinishedJob.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
- Enable GitHub Actions on your fork and push a commit to trigger a real CI run.
- (Optional, not required) Consider applying the same slice-before-lookup pattern to
RunningJobsServletin 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!
|
@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 Your approval predates the empty commit I pushed to trigger CI, so GitHub is showing review |
DanielLeens
left a comment
There was a problem hiding this comment.
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 newmatchingJobStates/toJobInfoJsonsplit, and theJobPageholder) - 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/limitslice instead of over every match.FinishedJobsServlet.java- branches onpageParams(req); when present, calls the new paged overload and writes{"data":..., "total": matches.size()}; when absent, still calls the original no-arggetJobsByStateJson(state)(now built from the samematchingJobStates/toJobInfoJsonhelpers, functionally identical to the old inline stream) and writes the raw array, exactly as before.PageBaseServlet.java- the newpageParams()+checkPageInRange()pair reproduces the oldwriteJsonWithPagination's validation exactly:page < 1still throws "Page number must be greater than 0", andstart > totalstill throws "Page number exceeds total pages" (not>=, so an empty result set withpage=1still doesn't throw - same as before).writeJsonPagewrites 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-shouldApplyPageBeforePerJobLookupsbuilds 25 job states, requests a 10-row page, and asserts bothpage.getData().size() == 10and, 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.shouldReturnNewestFinishedJobsFirstpins down ordering across a page boundary. Both are deterministic, mock-based (Mockito overIMap), 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.
|
Thanks @DanielLeens for the careful re-review, and especially for re-pulling the head into a clean worktree and confirming that 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):
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. |
|
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 |
|
@SEZ9 thanks for the list. Taking all seven here, not splitting 3 or 7. Addressing Item 2: It is intentional. The legacy Also, item 3 will entail that @nzw921rx yes, I will add them to seatunnel-benchmarks. On the margins, the numbers I posted are weak because I ran with The rest are code changes. I will push them as a single commit and comment again once CI is green. |
|
@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🚀 |
|
@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 Two ways to get a real baseline comparison:
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. |
…on across servlets
|
#11494 |
|
@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 You are correct that pagination cannot speed up the scan, and it does not. 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 The evidence I find most convincing is not a timing measurement at all. The test On the specific steps, the measurement used the existing There are two caveats on those numbers that you should weigh. The first is that the baseline benchmark calls the refactored On profiling, there is no flame graph or JFR yet. The only 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
left a comment
There was a problem hiding this comment.
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.
… incompatibility note
|
@nzw921rx The re-run is done, at the module's
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:
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: 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 |
nzw921rx
left a comment
There was a problem hiding this comment.
+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
left a comment
There was a problem hiding this comment.
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:rowsis now validated the same waypageis, the start-offset multiplication is computed inlongarithmetic and rejects overflow, the pre-existingwriteJsonWithPaginationpath (used by/running-jobsand/running-jobs/summary) is routed through the samepageParams()/checkPageInRange()helpers instead of duplicating the parsing logic, the new service overload has explicit precondition checks, and both the REST docs andincompatible-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#writeJsonWithPaginationthen keeps only 10 and discards 9,990. Benchmarked at ~9.2s / ~12.7GB allocated per call. - After:
matchingJobStatesfilters/sorts 10,000 lightweightJobStateentries (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.
|
@SEZ9 All seven are addressed as of
@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" ( 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 @nzw921rx flagging that for you since your approval was conditional on CI passing. The diff is confined to Locally, |
|
@DanielLeens thanks for re-pulling Your problem/fix summary matches my reading: the old 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:
If any of these are already addressed in |
|
@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
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. |
|
@SEZ9 @awsomesud347 Confirming I've re-checked the current head ( @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 The one thing still open is a real green 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. |
|
@DanielLeens thanks for confirming the head is still Your comment lays out how each of the earlier review points was handled: most by code change, the On CI: I understand from your account that the No further code changes requested from my side. Appreciate the careful back-and-forth. |
|
Thanks @SEZ9 — fair ask, a summary conclusion isn't the same as a pointer you can verify yourself. I re-pulled
On CI: no change since my last comment. I re-checked the fork directly ( |
|
Follow-up on the CI side, since a clean What is actually red. On fork run
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
Nothing in this diff can reach that path: the change is confined to Two things to move this along:
@SEZ9 the above is the evidence behind "cancelled, not failed" on |
|
CI is now green on @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 @SEZ9 this clears the clean |
|
Confirmed — I just re-pulled the current state directly rather than going by this thread: That was the one condition my approval was standing on, so with a clean 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. |
|
Thanks @awsomesud347 for the targeted rerun and @DanielLeens for verifying run 34089819303 and the 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:
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. |
|
@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 F1 and F5, F2, F4, F6, F3, F7, new file 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 |
|
@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. |
|
@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 — 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:
Once I have that, I'll check each location on |
|
@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 (
Nothing here has moved since my last pass, and Build is still green on |
|
@SEZ9 That comment is complete on GitHub, so your view may be truncating long comments. The short version, on
|
|
@awsomesud347 @SEZ9 Confirming I've seen this — nothing new for me to add here since my last pass (still @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. |
|
@awsomesud347 Thanks — the short version came through fine, and the pointers on 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:
One gap in the recap: F1 and F5 ( |
|
@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
For test coverage specifically,
So F1/F5 are covered both in source and in tests on the current head. Nothing here changes my |
|
@SEZ9 @DanielLeens has it right, and I verified every pointer against
|
davidzollo
left a comment
There was a problem hiding this comment.
+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 😄
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. Theanswer is
GET /metricsandGET /openmetrics, once per Prometheus scrape on the master. Thechain runs from
MetricsServletintoNodeExtension.getMetricFamilySamples(), which collectsfrom
JobMetricExports, which callsCoordinatorService.getJobCountMetrics(), which callsgetJobStatusData(). The only other caller is the CLI, which is one shot per invocation. The joblisting endpoints do not reach
getJobStatusData()at all, becauseJobInfoServicereads theIMaps 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 requestfixes.
JobInfoService.getJobsByStateJsonfetched every retained job, filtered and sorted it, thenperformed two IMap point lookups and a metric aggregation for each one, before
PageBaseServlet.writeJsonWithPaginationdiscarded everything outside the requested page. Arequest for
?page=1&rows=10against N retained jobs cost one full scan, two point lookups perstored job, and a metric aggregation per stored job. The
pageandrowsparameters bounded thesize 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:
Allocation from the same run, with
-prof gc: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 thelisting, 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 thancloses. Counting ten thousand retained jobs allocates roughly 200 MB per Prometheus scrape, almost
entirely from deserialising
JobStatevalues. Fixing that means avoiding the fetch to the masterrather 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, deserialisesand sorts every retained
JobStateon each request. Only the per-row work became lazy, so a pagedrequest 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 textcommand REST path returns the same payload as before.
The exception is input validation, which is deliberate and was requested in review.
pageandrowsare now validated on/finished-jobs/:state,/running-jobsand/running-jobs/summary,since all three go through
PageBaseServletand the latter two are served by the sameRunningJobsServletinstance. A value that is not an integer, or is not greater than 0, isrejected 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=0was previously accepted and returned an empty page, and a negativerowsproduced an internal error. Both now return 400. This is recorded in
incompatible-changes.mdandin the REST docs in both languages.
How was this patch tested?
Two tests were added to
JobInfoServiceNullSafetyTestfor the service overload.shouldApplyPageBeforePerJobLookupsseeds twenty five finished jobs, requests the first ten, andverifies 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.
shouldReturnNewestFinishedJobsFirstchecks that ordering by finish time descending is preserved,so paging over a growing history stays stable.
Nine tests were added in a new
FinishedJobsServletTestfor the servlet surface, covering zero andnegative
rows, a non integer value, a page below 1, an offset that overflows an int, a pagestarting beyond the end of the results, a page starting exactly at
total, and the routing betweenthe paged and unpaged service calls.
Making the servlet testable required widening
JobInfoService.JobPage's constructor from privateto 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-serverpasses with 470 tests, no failures and noerrors.
spotless:applyandmvnw -DskipTests verifyare clean.The timing and allocation figures came from the same run of the
seatunnel-benchmarksJMH harnessat its
BenchmarkBasedefaults, three forks with three warmup and five measurement iterations,with
-prof gc. The benchmark code itself is not included here. Note that the harness cannotcurrently run on Windows, because the
mini cluster home path created at
SeaTunnelEnvironmentContext.java:103is emitted into a doublequoted 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
incompatible-changes.mdentry in both languages.incompatible-changes.mdrecords the pagination validation change under## dev.