This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12904-5cf050be3ffc77c0065d67d4eb8af83f24a2a620 in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit e7f08dc52e9b7f349f4ec907c56c6420965c146e Author: Steven Zhao <[email protected]> AuthorDate: Sat Nov 28 13:34:47 2026 +0000 [Improve][Zeta] Mark unknown job-info responses with found:false (#12904) --- docs/en/engines/zeta/python-sdk.md | 10 + docs/en/engines/zeta/rest-api-job-lifecycle.md | 2 +- docs/en/engines/zeta/rest-api-v1.md | 20 +- docs/en/engines/zeta/rest-api-v2.md | 24 +- docs/zh/engines/zeta/python-sdk.md | 9 + docs/zh/engines/zeta/rest-api-job-lifecycle.md | 2 +- docs/zh/engines/zeta/rest-api-v1.md | 18 +- docs/zh/engines/zeta/rest-api-v2.md | 22 +- seatunnel-cli/seatunnel_cli/cli.py | 39 ++- seatunnel-cli/tests/test_diagnose_cli.py | 88 +++++++ .../seatunnel/engine/server/rest/RestConstant.java | 2 + .../engine/server/rest/service/JobInfoService.java | 4 +- .../rest/service/JobInfoServiceNullSafetyTest.java | 31 ++- .../src/locales/en_US/detail.ts | 10 + .../src/locales/zh_CN/detail.ts | 9 + .../seatunnel-engine-ui/src/service/job/types.ts | 2 + .../seatunnel-engine-ui/src/tests/detail.spec.ts | 264 ++++++++++++++++++++- .../seatunnel-engine-ui/src/views/jobs/detail.tsx | 94 ++++++-- .../seatunnel/endpoints/jobs.py | 22 ++ tools/seatunnel-python-sdk/tests/test_sdk.py | 47 ++++ 20 files changed, 672 insertions(+), 47 deletions(-) diff --git a/docs/en/engines/zeta/python-sdk.md b/docs/en/engines/zeta/python-sdk.md index a95a9e2412..5e8fe84bbc 100644 --- a/docs/en/engines/zeta/python-sdk.md +++ b/docs/en/engines/zeta/python-sdk.md @@ -69,6 +69,16 @@ with SeaTunnelClient(base_url="http://localhost:8080") as client: print(job_details) ``` +An unknown id is still an HTTP 200 response and contains `"found": false`. Use `job_exists` +when you only need an existence check; it also supports older servers that return only `jobId` +for an unknown job: + +```python +with SeaTunnelClient(base_url="http://localhost:8080") as client: + if not client.jobs.job_exists(jobId=12345): + print("The job id is unknown or has expired from finished-job history") +``` + ### Cluster Monitoring You can use the `cluster` property to get cluster information. diff --git a/docs/en/engines/zeta/rest-api-job-lifecycle.md b/docs/en/engines/zeta/rest-api-job-lifecycle.md index a026945a34..c4e725d1af 100644 --- a/docs/en/engines/zeta/rest-api-job-lifecycle.md +++ b/docs/en/engines/zeta/rest-api-job-lifecycle.md @@ -390,7 +390,7 @@ curl http://<master>:8080/overview | \ |---|---|---| | `HTTP 404` on any endpoint | REST API not enabled or wrong port | Set `enable-http: true` and check port | | `Connection refused` | Master not started or firewall blocking port | Verify master process is running; check firewall | -| `jobId not found` in `job-info` | Job has already finished or was never started | Query `/finished-jobs/:state` with the expected final state | +| `found: false` (or a status-less 200) in `job-info` | The id is unknown, or the job has expired from finished-job history | Query `/finished-jobs/:state` with the expected final state | | Submit returns `400 Bad Request` | Malformed JSON or missing required fields | Validate JSON; check `plugin_name` spelling | | `The job id ... has already been submitted and is not starting with a savepoint` | Resubmitting a job with a fixed `job.id` while history for that ID is still retained (cancelling does not clear it) | Submit a fresh job with a new `job.id`, or restore intentionally via the documented savepoint/restore flow | | `Unauthorized 401` | Basic authentication is enabled but no credentials were provided | Include `-u user:pass` | diff --git a/docs/en/engines/zeta/rest-api-v1.md b/docs/en/engines/zeta/rest-api-v1.md index 0590cd16ce..e214ef5c4a 100644 --- a/docs/en/engines/zeta/rest-api-v1.md +++ b/docs/en/engines/zeta/rest-api-v1.md @@ -417,7 +417,7 @@ None. } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` always be returned. +`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` are returned for a job the cluster knows; an unknown id returns the `found: false` response below. `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` will return when job is running. `finishTime`, `errorMsg` will return when job is finished. A running job also returns a `diagnostics` block (state timestamps and per-pipeline restore counts), @@ -445,14 +445,18 @@ not. | TableSinkWrite* | Per-table sink write attempts, key format `TableSinkWriteXXX#<table>` | | TableSinkCommitted* | Per-table sink committed metrics, key format `TableSinkCommittedXXX#<table>` | -When we can't get the job info, the response contains only the requested `jobId`: +An unknown id is still an HTTP 200 response with `found: false`: ```json { - "jobId" : "733584788375666689" + "jobId" : "<id>", + "found" : false } ``` +See the `/job-info/:jobId` section in [REST API V2](rest-api-v2.md) for details and the +older-server fallback. + </details> ------------------------------------------------------------------------------------------ @@ -531,18 +535,22 @@ This API has been deprecated, please use /hazelcast/rest/maps/job-info/:jobId in } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` always be returned. +`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` are returned for a job the cluster knows; an unknown id returns the `found: false` response below. `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` will return when job is running. `finishTime`, `errorMsg` will return when job is finished. -When we can't get the job info, the response contains only the requested `jobId`: +An unknown id is still an HTTP 200 response with `found: false`: ```json { - "jobId" : "733584788375666689" + "jobId" : "<id>", + "found" : false } ``` +See the `/job-info/:jobId` section in [REST API V2](rest-api-v2.md) for details and the +older-server fallback. + </details> ------------------------------------------------------------------------------------------ diff --git a/docs/en/engines/zeta/rest-api-v2.md b/docs/en/engines/zeta/rest-api-v2.md index efd8ae8d75..3af333030a 100644 --- a/docs/en/engines/zeta/rest-api-v2.md +++ b/docs/en/engines/zeta/rest-api-v2.md @@ -698,7 +698,8 @@ This endpoint helps troubleshoot why jobs stay in `PENDING` by showing the pendi } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` always be returned. +`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` are returned for a job the +cluster knows. An unknown id returns the `found: false` response described below. `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` will return when job is running. `finishTime`, `errorMsg` will return when job is finished. `diagnostics` will return when the job is running and its diagnostics can be read from the master @@ -746,14 +747,21 @@ previous master are not carried over. | pipelines[].stateTimestamps | Epoch millis when the pipeline entered each state. After a restore, the timestamps of the new attempt overwrite the previous ones | | totalPipelineRestoreCount | Sum of `restoreCount` over all pipelines of the job | -When we can't get the job info, the response contains only the requested `jobId`: +An unknown id is still an HTTP 200 response. It contains the requested id and an explicit +`found: false` marker: ```json { - "jobId" : "733584788375666689" + "jobId" : "733584788375093248", + "found" : false } ``` +`found: false` means the cluster has no retained record for the id: the id may be wrong, or the +job may have expired from the finished-job history. Successful payloads keep their existing shape +and do not contain `found`. Older engines return only `jobId` for an unknown id; clients should +treat a missing `jobStatus` as the compatibility fallback. + </details> ------------------------------------------------------------------------------------------ @@ -832,18 +840,22 @@ This API has been deprecated, please use /job-info/:jobId instead } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` always be returned. +`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` are returned for a job the cluster knows; an unknown id returns the `found: false` response below. `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` will return when job is running. `finishTime`, `errorMsg` will return when job is finished. -When we can't get the job info, the response contains only the requested `jobId`: +An unknown id is still an HTTP 200 response with `found: false`: ```json { - "jobId" : "733584788375666689" + "jobId" : "<id>", + "found" : false } ``` +See the `/job-info/:jobId` section in [REST API V2](rest-api-v2.md) for details and the +older-server fallback. + </details> ------------------------------------------------------------------------------------------ diff --git a/docs/zh/engines/zeta/python-sdk.md b/docs/zh/engines/zeta/python-sdk.md index 3d64c6891e..773a6f05a7 100644 --- a/docs/zh/engines/zeta/python-sdk.md +++ b/docs/zh/engines/zeta/python-sdk.md @@ -70,6 +70,15 @@ with SeaTunnelClient(base_url="http://localhost:8080") as client: print(job_details) ``` +未知 id 仍会返回 HTTP 200,并在响应中带上 `"found": false`。如果只需要判断作业是否存在, +可以使用 `job_exists`;它也兼容旧版本引擎(旧版本对未知 id 只返回 `jobId`): + +```python +with SeaTunnelClient(base_url="http://localhost:8080") as client: + if not client.jobs.job_exists(jobId=12345): + print("该作业 ID 不存在,或已从已完成作业历史中过期") +``` + ### 集群监控 您可以使用 `cluster` 属性来获取集群信息。 diff --git a/docs/zh/engines/zeta/rest-api-job-lifecycle.md b/docs/zh/engines/zeta/rest-api-job-lifecycle.md index 08d67efb0b..203defa1dd 100644 --- a/docs/zh/engines/zeta/rest-api-job-lifecycle.md +++ b/docs/zh/engines/zeta/rest-api-job-lifecycle.md @@ -378,7 +378,7 @@ curl http://<master>:8080/overview | \ |---|---|---| | 任意端点返回 `HTTP 404` | REST API 未启用或端口不对 | 设置 `enable-http: true` 并检查端口 | | `Connection refused` | Master 未启动或防火墙拦截 | 确认 Master 进程在运行;检查防火墙 | -| `job-info` 中找不到 `jobId` | 作业已完成或未启动 | 按预期终态改用 `/finished-jobs/:state` 查询 | +| `job-info` 返回 `found: false`(或无状态的 200) | id 不存在,或作业已从已完成作业历史中过期 | 按预期终态改用 `/finished-jobs/:state` 查询 | | 提交返回 `400 Bad Request` | JSON 格式错误或缺少必填字段 | 验证 JSON;检查 `plugin_name` 拼写 | | `The job id ... has already been submitted and is not starting with a savepoint` | 使用固定 `job.id` 重复提交,而该 ID 的历史记录仍被保留(取消作业不会清除) | 换一个新的 `job.id` 重新提交作业;或按文档中的 Savepoint/恢复流程有意地进行恢复 | | `Unauthorized 401` | 已启用 Basic Auth 但未提供凭据 | 添加 `-u user:pass` | diff --git a/docs/zh/engines/zeta/rest-api-v1.md b/docs/zh/engines/zeta/rest-api-v1.md index 9b26354e83..653126ecb9 100644 --- a/docs/zh/engines/zeta/rest-api-v1.md +++ b/docs/zh/engines/zeta/rest-api-v1.md @@ -436,7 +436,7 @@ network: } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` 字段总会返回. +对于集群中存在的 Job,会返回 `jobId`、`jobName`、`jobStatus`、`createTime`、`startTime`、`jobDag`、`metrics` 字段;未知 id 会返回下方的 `found: false` 响应。 `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` 字段在Job在RUNNING状态时会返回 `finishTime`, `errorMsg` 字段在Job结束时会返回,结束状态为不为RUNNING,可能为FINISHED,可能为CANCELED 运行中的Job还会返回 `diagnostics` 字段(状态时间戳与各 Pipeline 的恢复次数),字段说明见 [REST API V2](rest-api-v2.md)。该字段只在本接口返回,`/running-jobs` 不返回。 @@ -462,14 +462,17 @@ network: | TableSinkWrite* | 按表汇总的 Sink 写入尝试,键格式 `TableSinkWriteXXX#<表>` | | TableSinkCommitted* | 按表汇总的 Sink 已提交指标,键格式 `TableSinkCommittedXXX#<表>` | -当我们查询不到这个Job时,返回结果只包含请求的 `jobId`: +未知 id 仍会返回 HTTP 200,并带有 `found: false`: ```json { - "jobId" : "733584788375666689" + "jobId" : "<id>", + "found" : false } ``` +完整说明及旧版本引擎的兼容方式请参阅 [REST API V2](rest-api-v2.md) 的 `/job-info/:jobId` 章节。 + </details> ------------------------------------------------------------------------------------------ @@ -525,18 +528,21 @@ network: } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` 字段总会返回. +对于集群中存在的 Job,会返回 `jobId`、`jobName`、`jobStatus`、`createTime`、`startTime`、`jobDag`、`metrics` 字段;未知 id 会返回下方的 `found: false` 响应。 `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` 字段在Job在RUNNING状态时会返回 `finishTime`, `errorMsg` 字段在Job结束时会返回,结束状态为不为RUNNING,可能为FINISHED,可能为CANCELED -当我们查询不到这个Job时,返回结果只包含请求的 `jobId`: +未知 id 仍会返回 HTTP 200,并带有 `found: false`: ```json { - "jobId" : "733584788375666689" + "jobId" : "<id>", + "found" : false } ``` +完整说明及旧版本引擎的兼容方式请参阅 [REST API V2](rest-api-v2.md) 的 `/job-info/:jobId` 章节。 + </details> ------------------------------------------------------------------------------------------ diff --git a/docs/zh/engines/zeta/rest-api-v2.md b/docs/zh/engines/zeta/rest-api-v2.md index c94f3db1fc..98a3a20b07 100644 --- a/docs/zh/engines/zeta/rest-api-v2.md +++ b/docs/zh/engines/zeta/rest-api-v2.md @@ -689,7 +689,8 @@ seatunnel: } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` 字段总会返回. +对于集群中存在的 Job,会返回 `jobId`、`jobName`、`jobStatus`、`createTime`、`startTime`、`jobDag`、`metrics` 字段。 +未知 id 会返回下方描述的 `found: false` 响应。 `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` 字段在Job在RUNNING状态时会返回 `finishTime`, `errorMsg` 字段在Job结束时会返回,结束状态为不为RUNNING,可能为FINISHED,可能为CANCELED `diagnostics` 字段在Job运行中且能从Master节点读取到诊断信息时返回。它属于辅助信息,读取失败时该字段会被省略,不会导致请求失败。该字段只在本接口返回,`/running-jobs` 不返回:为列表中的每个Job收集诊断信息会额外增加一次到Master的请求。 @@ -731,14 +732,20 @@ seatunnel: | pipelines[].stateTimestamps | Pipeline 进入各状态的时间戳(毫秒)。发生恢复后,新一轮的时间戳会覆盖上一轮 | | totalPipelineRestoreCount | Job 下所有 Pipeline 的 `restoreCount` 之和 | -当我们查询不到这个Job时,返回结果只包含请求的 `jobId`: +当查询的 Job 不存在时,仍然返回 HTTP 200,但响应中只包含请求的 id 和显式的 +`found: false` 标记: ```json { - "jobId" : "733584788375666689" + "jobId" : "733584788375093248", + "found" : false } ``` +`found: false` 表示当前集群没有保留该 id 的记录:可能是 id 写错了,也可能是作业已从已完成作业历史中过期。 +成功查询的响应保持原有结构,不包含 `found` 字段。旧版本引擎对未知 id 只返回 `jobId`;客户端可以将 +缺少 `jobStatus` 作为兼容判断。 + </details> ------------------------------------------------------------------------------------------ @@ -817,18 +824,21 @@ seatunnel: } ``` -`jobId`, `jobName`, `jobStatus`, `createTime`, `startTime`, `jobDag`, `metrics` 字段总会返回. +对于集群中存在的 Job,会返回 `jobId`、`jobName`、`jobStatus`、`createTime`、`startTime`、`jobDag`、`metrics` 字段;未知 id 会返回下方的 `found: false` 响应。 `envOptions`, `pluginJarsUrls`, `isStartWithSavePoint` 字段在Job在RUNNING状态时会返回 `finishTime`, `errorMsg` 字段在Job结束时会返回,结束状态为不为RUNNING,可能为FINISHED,可能为CANCELED -当我们查询不到这个Job时,返回结果只包含请求的 `jobId`: +未知 id 仍会返回 HTTP 200,并带有 `found: false`: ```json { - "jobId" : "733584788375666689" + "jobId" : "<id>", + "found" : false } ``` +完整说明及旧版本引擎的兼容方式请参阅 [REST API V2](rest-api-v2.md) 的 `/job-info/:jobId` 章节。 + </details> ------------------------------------------------------------------------------------------ diff --git a/seatunnel-cli/seatunnel_cli/cli.py b/seatunnel-cli/seatunnel_cli/cli.py index 225fadfc93..549fd5c1e9 100644 --- a/seatunnel-cli/seatunnel_cli/cli.py +++ b/seatunnel-cli/seatunnel_cli/cli.py @@ -1358,13 +1358,38 @@ class SeaTunnelCLI: poll_interval = 2 max_polls = 150 # 5 minutes max last_status = "" + missing_response_seen = False for _ in range(max_polls): time.sleep(poll_interval) try: info = rest.request_json(f"{api_base}/job-info/{job_id}", timeout=10) - status = info.get("jobStatus", "UNKNOWN") + if isinstance(info, dict) and info.get("found") is False: + self.console.print( + f" [error]Job {job_id} is no longer present in the cluster's running " + f"or finished-job maps.[/error] Check the master logs; it may have been " + f"removed by a master restart without persisted state, or expired from " + f"the finished-job history." + ) + return + + status = info.get("jobStatus") if isinstance(info, dict) else None + if not isinstance(status, str) or not status.strip(): + # A status-less 200 can be a transient master failover on older + # servers, so tolerate one before declaring the job unknown. + if not missing_response_seen: + missing_response_seen = True + continue + self.console.print( + f" [error]The engine returned no job status for job {job_id} twice." + f"[/error] This looks like a response-shape or master-failover problem; " + f"retry the command or check the master logs." + ) + return + + missing_response_seen = False + status = status.strip() if status != last_status: last_status = status self.console.print(f" Status: [bold]{status}[/bold]", style="info") @@ -1654,7 +1679,17 @@ def run_diagnose(job_id: str, console: Console) -> int: # matches, and the output reads "Nothing to report" -- i.e. "your job is # fine" about a job that does not exist. A non-object body (a bare `null` # or a list from a proxy) is the same situation and is caught here too, - # before anything calls .get() on it. + # before anything calls .get() on it. Newer servers mark the same case + # explicitly with `found: false`. + if isinstance(job_info, dict) and job_info.get("found") is False: + console.print( + f"[error]No job {escape(job_id)} on the cluster at " + f"{escape(_ENGINE_API_BASE)}.[/error] The engine marked it as unknown: " + f"either the id is wrong, or the job has been evicted from the " + f"finished-job history." + ) + return 1 + status = job_info.get("jobStatus") if isinstance(job_info, dict) else None if not isinstance(status, str) or not status.strip(): console.print( diff --git a/seatunnel-cli/tests/test_diagnose_cli.py b/seatunnel-cli/tests/test_diagnose_cli.py index 0d920ed4f1..98d9bde80a 100644 --- a/seatunnel-cli/tests/test_diagnose_cli.py +++ b/seatunnel-cli/tests/test_diagnose_cli.py @@ -305,6 +305,18 @@ def test_an_unknown_job_id_is_reported_from_the_response_the_engine_really_sends assert "Nothing to report" not in out +def test_an_unknown_job_marked_by_found_false_is_reported(engine): + # Newer engines add an explicit marker to the same 200 response. + engine.script = lambda h: (200, json.dumps({"jobId": "999999999999999999", "found": False})) + + code, out = _run("999999999999999999") + + assert code == 1 + assert "No job 999999999999999999" in out + assert "marked it as unknown" in out + assert "Nothing to report" not in out + + def test_a_non_object_json_body_does_not_crash(engine): # A bare `null` or a list (a proxy, or a future response shape) reaches # the same path and must not raise AttributeError. @@ -317,6 +329,82 @@ def test_a_non_object_json_body_does_not_crash(engine): assert "No job 852" in out [email protected]( + "responses, expected_calls, expected_message", + [ + ([{"jobId": "852", "found": False}], 1, "no longer present"), + ([{"jobId": "852"}], 2, "returned no job status"), + # `None` is the decoded body of a JSON `null`: a non-dict 200 is + # treated as status-less, so the explicit marker on the next poll + # still has to win over the "no status twice" branch. + ([None, {"jobId": "852", "found": False}], 2, "no longer present"), + ( + [ + {"jobId": "852"}, + {"jobId": "852", "jobStatus": "RUNNING"}, + {"jobId": "852"}, + {"jobId": "852", "found": False}, + ], + 4, + "no longer present", + ), + ], + ids=[ + "new-server-marker", + "old-server-status-less", + "non-dict-body-then-marker", + "status-less-good-status-less-then-marker", + ], +) +def test_polling_stops_when_the_job_is_not_known( + monkeypatch, responses, expected_calls, expected_message +): + cli = object.__new__(cli_module.SeaTunnelCLI) + console = Console(theme=cli_module.THEME, width=200, record=True) + cli.console = console + calls = {"count": 0} + remaining = iter(responses) + + def fake_request_json(url, timeout=10): + calls["count"] += 1 + # Keep answering status-less once the scripted bodies run out: a poll + # that fails to stop on the scripted responses then hits the max-poll + # bound, so the call-count assertion reports the regression instead of + # the fake raising StopIteration into the poller's error handling. + return next(remaining, {"jobId": "852"}) + + monkeypatch.setattr(cli_module.rest, "request_json", fake_request_json) + monkeypatch.setattr(cli_module.time, "sleep", lambda seconds: None) + + cli._poll_job_status("http://127.0.0.1:8080", "852") + + out = " ".join(console.export_text().split()) + assert calls["count"] == expected_calls + assert expected_message in out + + +def test_polling_recovers_from_one_status_less_response(monkeypatch): + cli = object.__new__(cli_module.SeaTunnelCLI) + console = Console(theme=cli_module.THEME, width=200, record=True) + cli.console = console + responses = iter([{"jobId": "852"}, {"jobId": "852", "jobStatus": "FINISHED"}]) + calls = {"count": 0} + + def fake_request_json(url, timeout=10): + calls["count"] += 1 + return next(responses) + + monkeypatch.setattr(cli_module.rest, "request_json", fake_request_json) + monkeypatch.setattr(cli_module.time, "sleep", lambda seconds: None) + + cli._poll_job_status("http://127.0.0.1:8080", "852") + + out = " ".join(console.export_text().split()) + assert calls["count"] == 2 + assert "Status: FINISHED" in out + assert "not known" not in out + + def test_a_real_404_is_still_handled(engine): # Jetty does not send it for a missing job, but a proxy or a different # engine build can, and that branch still has to say something useful. diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java index ab2c05feb1..c651be734c 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/RestConstant.java @@ -22,6 +22,8 @@ public class RestConstant { public static final String JOB_ID = "jobId"; + public static final String FOUND = "found"; + public static final String JOB_NAME = "jobName"; public static final String IS_START_WITH_SAVE_POINT = "isStartWithSavePoint"; diff --git a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java index 5a9707e2f1..3203268743 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java +++ b/seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/service/JobInfoService.java @@ -111,7 +111,9 @@ public class JobInfoService extends BaseService { return getJobInfoJson( finishedJobState, finishedJobMetrics.toJsonString(), finishedJobDAGInfo); } else { - return new JsonObject().add(RestConstant.JOB_ID, jobId.toString()); + return new JsonObject() + .add(RestConstant.JOB_ID, jobId.toString()) + .add(RestConstant.FOUND, false); } } diff --git a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceNullSafetyTest.java b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceNullSafetyTest.java index 09b89097b2..186fbf352c 100644 --- a/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceNullSafetyTest.java +++ b/seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/rest/service/JobInfoServiceNullSafetyTest.java @@ -165,7 +165,7 @@ class JobInfoServiceNullSafetyTest { } @Test - void shouldReturnJobIdOnlyWhenFinishedMetricsIsMissing() { + void shouldReturnFinishedPayloadWithEmptyMetricsWhenMetricsAreMissing() { JobHistoryService.JobState jobState = buildJobState(jobId, 1000L, 2000L); when(runningJobInfoMap.get(jobId)).thenReturn(null); @@ -176,6 +176,7 @@ class JobInfoServiceNullSafetyTest { Assertions.assertNotNull(result); Assertions.assertEquals(jobId.toString(), result.getString(RestConstant.JOB_ID, null)); + Assertions.assertNull(result.get(RestConstant.FOUND)); } @Test @@ -199,10 +200,11 @@ class JobInfoServiceNullSafetyTest { Assertions.assertNotNull(result); Assertions.assertEquals(jobId.toString(), result.getString(RestConstant.JOB_ID, null)); Assertions.assertEquals(dagJson.toString(), result.get(RestConstant.JOB_DAG).toString()); + Assertions.assertNull(result.get(RestConstant.FOUND)); } @Test - void shouldReturnJobIdOnlyWhenFinishedStateDoesNotExist() { + void shouldMarkUnknownJobAsNotFound() { when(runningJobInfoMap.get(jobId)).thenReturn(null); when(finishedJobStateMap.get(jobId)).thenReturn(null); when(finishedJobMetricsMap.get(jobId)).thenReturn(null); @@ -211,6 +213,31 @@ class JobInfoServiceNullSafetyTest { Assertions.assertNotNull(result); Assertions.assertEquals(jobId.toString(), result.getString(RestConstant.JOB_ID, null)); + Assertions.assertFalse(result.getBoolean(RestConstant.FOUND, true)); + Assertions.assertNull(result.get(RestConstant.JOB_STATUS)); + } + + @Test + void shouldNotAddFoundMarkerToRunningJobPayload() { + JobInfo runningJob = mock(JobInfo.class); + when(runningJobInfoMap.get(jobId)).thenReturn(runningJob); + // The full running payload depends on the coordinator and DAG subsystems; stub only the + // conversion so the test can assert that the running branch adds no marker of its own. + JobInfoService service = + new JobInfoService(nodeEngine) { + @Override + protected JsonObject convertToJson(JobInfo jobInfo, long id) { + return new JsonObject() + .add(RestConstant.JOB_ID, String.valueOf(id)) + .add(RestConstant.JOB_STATUS, JobStatus.RUNNING.name()); + } + }; + + JsonObject result = service.getJobInfoJson(jobId); + + Assertions.assertEquals( + JobStatus.RUNNING.name(), result.getString(RestConstant.JOB_STATUS, null)); + Assertions.assertNull(result.get(RestConstant.FOUND)); } @Test diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts index af6b27456c..ad8974809f 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/en_US/detail.ts @@ -19,6 +19,16 @@ export default { id: 'ID', createTime: 'Create Time', duration: 'Duration', + notFound: { + title: 'Job not found', + description: + 'Job {jobId} is unknown to this cluster, or it has expired from the finished-job history.' + }, + loadError: { + title: 'Could not load job', + description: 'Could not load job {jobId}: {error}', + refresh: 'Could not refresh job {jobId}: {error}. Retrying.' + }, tabs: { overview: 'Overview', exception: 'Exception', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts index a0ae8626a2..f39e5c0f46 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/locales/zh_CN/detail.ts @@ -19,6 +19,15 @@ export default { id: 'ID', createTime: '开始时间', duration: '运行时间', + notFound: { + title: '作业不存在', + description: '作业 {jobId} 在当前集群中不存在,或已从已完成作业历史中过期。' + }, + loadError: { + title: '加载作业失败', + description: '无法加载作业 {jobId}:{error}', + refresh: '刷新作业 {jobId} 失败:{error},正在重试。' + }, tabs: { overview: '概览', exception: '异常', diff --git a/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts b/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts index dd90c1066f..26de287825 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/service/job/types.ts @@ -79,6 +79,8 @@ export type JobStatus = | 'UNKNOWABLE' export interface Job { jobId: string + /** Present only on the additive unknown-job response; successful payloads omit it. */ + found?: boolean jobName: string jobStatus: JobStatus errorMsg: string diff --git a/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts b/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts index 6dfbabdfdc..af2709830f 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts +++ b/seatunnel-engine/seatunnel-engine-ui/src/tests/detail.spec.ts @@ -15,7 +15,7 @@ * limitations under the License. */ -import { describe, test, expect, vi, beforeEach } from 'vitest' +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' import { createApp, h } from 'vue' import { createPinia, setActivePinia } from 'pinia' @@ -25,6 +25,21 @@ import detail from '@/views/jobs/detail' import { getJobInfo } from '@/service/job' import type { Job } from '@/service/job/types' +const { warningSpy } = vi.hoisted(() => ({ warningSpy: vi.fn() })) + +vi.mock('naive-ui', async (importOriginal) => { + const actual = await importOriginal<typeof import('naive-ui')>() + return { + ...actual, + useMessage: () => ({ + warning: warningSpy, + error: vi.fn(), + success: vi.fn(), + info: vi.fn() + }) + } +}) + vi.mock('@/service/job', () => ({ getJobInfo: vi.fn(), getRunningJobInfo: vi.fn() @@ -69,6 +84,10 @@ describe('detail', () => { setActivePinia(createPinia()) }) + afterEach(() => { + vi.useRealTimers() + }) + test('should not display NaN when tablePaths does not match metrics keys', async () => { const mockJob = { jobId: '123456789', @@ -139,4 +158,247 @@ describe('detail', () => { expect(wrapper.text()).not.toContain('NaN') }) + + test('should show a missing-job state and stop polling for found:false', async () => { + vi.useFakeTimers() + vi.mocked(getJobInfo).mockClear() + vi.mocked(getJobInfo).mockResolvedValue({ + jobId: '123456789', + found: false + } as unknown as Job) + + const pinia = createPinia() + setActivePinia(pinia) + const wrapper = mount( + { + setup() { + return () => h(NMessageProvider, null, { default: () => h(detail) }) + } + }, + { + global: { + plugins: [i18n, pinia] + } + } + ) + + await flushPromises() + + expect(wrapper.text()).toContain('Job not found') + expect(wrapper.text()).toContain('123456789') + expect(wrapper.text()).not.toContain('Create Time') + expect(getJobInfo).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(6000) + await flushPromises() + + expect(getJobInfo).toHaveBeenCalledTimes(1) + }) + + test('should treat two status-less responses from an older server as missing', async () => { + vi.useFakeTimers() + vi.mocked(getJobInfo).mockClear() + vi.mocked(getJobInfo).mockResolvedValue({ jobId: '123456789' } as unknown as Job) + + const pinia = createPinia() + setActivePinia(pinia) + const wrapper = mount( + { + setup() { + return () => h(NMessageProvider, null, { default: () => h(detail) }) + } + }, + { + global: { + plugins: [i18n, pinia] + } + } + ) + + await flushPromises() + expect(wrapper.text()).not.toContain('Job not found') + + vi.advanceTimersByTime(5000) + await flushPromises() + + expect(getJobInfo).toHaveBeenCalledTimes(2) + expect(wrapper.text()).toContain('Job not found') + }) + + test('should recover from one status-less response', async () => { + vi.useFakeTimers() + vi.mocked(getJobInfo).mockClear() + vi.mocked(getJobInfo) + .mockResolvedValueOnce({ jobId: '123456789' } as unknown as Job) + .mockResolvedValueOnce({ + jobId: '123456789', + jobName: 'Recovered', + jobStatus: 'FINISHED', + errorMsg: '', + createTime: '2026-05-21 10:00:00', + finishTime: '2026-05-21 11:00:00', + metrics: {}, + jobDag: { jobId: '123456789', pipelineEdges: {}, vertexInfoMap: [] }, + pluginJarsUrls: [] + } as unknown as Job) + + const pinia = createPinia() + setActivePinia(pinia) + const wrapper = mount( + { + setup() { + return () => h(NMessageProvider, null, { default: () => h(detail) }) + } + }, + { + global: { + plugins: [i18n, pinia] + } + } + ) + + await flushPromises() + expect(wrapper.text()).not.toContain('Job not found') + + vi.advanceTimersByTime(5000) + await flushPromises() + + expect(getJobInfo).toHaveBeenCalledTimes(2) + expect(wrapper.text()).toContain('Recovered') + }) + + test('should show an error result when getJobInfo rejects', async () => { + vi.mocked(getJobInfo).mockRejectedValue(new Error('master unavailable')) + + const pinia = createPinia() + setActivePinia(pinia) + const wrapper = mount( + { + setup() { + return () => h(NMessageProvider, null, { default: () => h(detail) }) + } + }, + { + global: { + plugins: [i18n, pinia] + } + } + ) + + await flushPromises() + + expect(wrapper.text()).toContain('Could not load job') + expect(wrapper.text()).toContain('master unavailable') + }) + + test('should keep the loaded job when a refresh is rejected', async () => { + vi.useFakeTimers() + vi.mocked(getJobInfo).mockClear() + const runningJob = { + jobId: '123456789', + jobName: 'Still Here', + jobStatus: 'RUNNING', + errorMsg: '', + createTime: '2026-05-21 10:00:00', + metrics: {}, + jobDag: { jobId: '123456789', pipelineEdges: {}, vertexInfoMap: [] }, + pluginJarsUrls: [] + } as unknown as Job + vi.mocked(getJobInfo) + .mockResolvedValueOnce(runningJob) + .mockRejectedValueOnce(new Error('temporary blip')) + .mockResolvedValueOnce({ ...runningJob, jobName: 'Recovered' } as Job) + + const pinia = createPinia() + setActivePinia(pinia) + const wrapper = mount( + { + setup() { + return () => h(NMessageProvider, null, { default: () => h(detail) }) + } + }, + { + global: { + plugins: [i18n, pinia] + } + } + ) + + await flushPromises() + expect(wrapper.text()).toContain('Still Here') + + vi.advanceTimersByTime(5000) + await flushPromises() + + expect(getJobInfo).toHaveBeenCalledTimes(2) + expect(wrapper.text()).toContain('Still Here') + expect(wrapper.text()).not.toContain('Could not load job') + + vi.advanceTimersByTime(5000) + await flushPromises() + + expect(getJobInfo).toHaveBeenCalledTimes(3) + expect(wrapper.text()).toContain('Recovered') + }) + + test('should warn once per error streak and reset after a successful refresh', async () => { + vi.useFakeTimers() + warningSpy.mockClear() + vi.mocked(getJobInfo).mockClear() + const runningJob = { + jobId: '123456789', + jobName: 'Still Here', + jobStatus: 'RUNNING', + errorMsg: '', + createTime: '2026-05-21 10:00:00', + metrics: {}, + jobDag: { jobId: '123456789', pipelineEdges: {}, vertexInfoMap: [] }, + pluginJarsUrls: [] + } as unknown as Job + vi.mocked(getJobInfo) + .mockResolvedValueOnce(runningJob) + .mockRejectedValueOnce(new Error('blip')) + .mockRejectedValueOnce(new Error('blip')) + .mockRejectedValueOnce(new Error('other blip')) + .mockResolvedValueOnce({ ...runningJob, jobName: 'Recovered' } as Job) + .mockRejectedValueOnce(new Error('blip')) + + const pinia = createPinia() + setActivePinia(pinia) + mount( + { + setup() { + return () => h(NMessageProvider, null, { default: () => h(detail) }) + } + }, + { + global: { + plugins: [i18n, pinia] + } + } + ) + + await flushPromises() + expect(warningSpy).not.toHaveBeenCalled() + + vi.advanceTimersByTime(5000) + await flushPromises() + expect(warningSpy).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(5000) + await flushPromises() + expect(warningSpy).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(5000) + await flushPromises() + expect(warningSpy).toHaveBeenCalledTimes(2) + + vi.advanceTimersByTime(5000) + await flushPromises() + expect(warningSpy).toHaveBeenCalledTimes(2) + + vi.advanceTimersByTime(5000) + await flushPromises() + expect(warningSpy).toHaveBeenCalledTimes(3) + }) }) diff --git a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx index 1e113c0056..c2ff11493d 100644 --- a/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx +++ b/seatunnel-engine/seatunnel-engine-ui/src/views/jobs/detail.tsx @@ -26,6 +26,7 @@ import { NDrawerContent, NButton, NSpace, + NResult, useMessage } from 'naive-ui' import { computed, defineComponent, onUnmounted, reactive, ref, watch } from 'vue' @@ -84,25 +85,72 @@ export default defineComponent({ const jobId = route.params.jobId as string pinStore.ensureJob(jobId) const job = reactive({} as Job) + const missing = ref(false) + const loadError = ref('') const duration = ref('') let timer: NodeJS.Timeout let fetchTimer: NodeJS.Timeout + let statusLessSeen = false + let lastRefreshError = '' const fetch = async () => { - const res = await getJobInfo(jobId) - Object.assign(job, res) - clearInterval(timer) - const d = parse(res.createTime, 'yyyy-MM-dd HH:mm:ss', new Date()) - duration.value = getRemainTime(Math.abs(Date.now() - d.getTime())) - if (isTerminalState(job.jobStatus)) { + try { + const res = await getJobInfo(jobId) + if (res.found === false) { + missing.value = true + loadError.value = '' + clearInterval(timer) + clearTimeout(fetchTimer) + pinStore.clear() + return + } + if (!res.jobStatus) { + // Older servers omit the marker. Tolerate one status-less response during a + // master failover, then treat a repeat as a missing job. + if (!statusLessSeen) { + statusLessSeen = true + fetchTimer = setTimeout(fetch, 5000) + return + } + missing.value = true + loadError.value = '' + clearInterval(timer) + clearTimeout(fetchTimer) + pinStore.clear() + return + } + statusLessSeen = false + lastRefreshError = '' + loadError.value = '' + Object.assign(job, res) + clearInterval(timer) + const d = parse(res.createTime, 'yyyy-MM-dd HH:mm:ss', new Date()) + duration.value = getRemainTime(Math.abs(Date.now() - d.getTime())) + if (isTerminalState(job.jobStatus)) { + clearTimeout(fetchTimer) + pinStore.clear() + return + } + fetchTimer = setTimeout(fetch, 5000) + if (isRunningState(job.jobStatus)) { + timer = setInterval(() => { + duration.value = getRemainTime(Math.abs(Date.now() - d.getTime())) + }, 1000) + } + } catch (e) { + const error = e instanceof Error ? e.message : String(e) + clearInterval(timer) clearTimeout(fetchTimer) - pinStore.clear() - return - } - fetchTimer = setTimeout(fetch, 5000) - if (isRunningState(job.jobStatus)) { - timer = setInterval(() => { - duration.value = getRemainTime(Math.abs(Date.now() - d.getTime())) - }, 1000) + if (!job.jobStatus) { + loadError.value = error + pinStore.clear() + return + } + loadError.value = '' + if (lastRefreshError !== error) { + lastRefreshError = error + message.warning(t('detail.loadError.refresh', { jobId, error })) + } + fetchTimer = setTimeout(fetch, 5000) } } @@ -558,7 +606,21 @@ export default defineComponent({ return { onClick: () => onFocus(row) } } - return () => ( + const renderMissing = () => ( + <div class="job-detail-page w-full bg-white border border-gray-100 rounded-xl"> + <NResult + status={missing.value ? '404' : 'error'} + title={missing.value ? t('detail.notFound.title') : t('detail.loadError.title')} + description={ + missing.value + ? t('detail.notFound.description', { jobId }) + : t('detail.loadError.description', { jobId, error: loadError.value }) + } + /> + </div> + ) + + const renderContent = () => ( <div class="job-detail-page w-full bg-white border border-gray-100 rounded-xl"> <div class="job-detail-title font-bold text-xl"> <span>{job.jobName}</span> @@ -727,5 +789,7 @@ export default defineComponent({ </div> </div> ) + + return () => (missing.value || loadError.value ? renderMissing() : renderContent()) } }) diff --git a/tools/seatunnel-python-sdk/seatunnel/endpoints/jobs.py b/tools/seatunnel-python-sdk/seatunnel/endpoints/jobs.py index ec1cdd435e..dcf28c6905 100644 --- a/tools/seatunnel-python-sdk/seatunnel/endpoints/jobs.py +++ b/tools/seatunnel-python-sdk/seatunnel/endpoints/jobs.py @@ -80,9 +80,31 @@ class JobsApi: def get_job_details(self, jobId: int): """ Return Details Of A Job + + An unknown id is still an HTTP 200 response. New servers mark it with + ``"found": false``; successful payloads keep their existing shape and + omit the marker. Older servers return only ``jobId`` for an unknown id. """ return self.client.request(HttpMethod.GET, f"/job-info/{jobId}") + def job_exists(self, jobId: int) -> bool: + """ + Return whether the cluster has a retained record for the job id. + + New servers set ``found`` explicitly. For older servers, which return + only ``jobId`` for an unknown job, the presence of ``jobStatus`` is + used as the compatibility fallback. + """ + details = self.get_job_details(jobId) + if not isinstance(details, dict): + raise TypeError( + f"/job-info/{jobId} returned a non-JSON object response: " + f"{type(details).__name__}" + ) + if "found" in details: + return bool(details["found"]) + return "jobStatus" in details + def get_finished_jobs_info(self, state: Optional[JobStatus] = None): """ Return Details Of A Job diff --git a/tools/seatunnel-python-sdk/tests/test_sdk.py b/tools/seatunnel-python-sdk/tests/test_sdk.py index b9d9d6cc09..bc836631ad 100644 --- a/tools/seatunnel-python-sdk/tests/test_sdk.py +++ b/tools/seatunnel-python-sdk/tests/test_sdk.py @@ -111,6 +111,53 @@ class SeaTunnelSdkTest(unittest.TestCase): self.assertEqual("http://localhost:8080/logs/733584788375666689", url) self.assertEqual({"format": "json"}, kwargs["params"]) + def test_job_exists_uses_explicit_found_marker(self): + response = httpx.Response( + 200, + json={"jobId": "12345", "found": False}, + request=httpx.Request("GET", "http://localhost:8080/job-info/12345"), + ) + session = RecordingSession(response=response) + sdk = self.create_client(session) + + self.assertFalse(sdk.jobs.job_exists(12345)) + self.assertEqual({"jobId": "12345", "found": False}, sdk.jobs.get_job_details(12345)) + + def test_job_exists_falls_back_to_job_status_for_older_servers(self): + response = httpx.Response( + 200, + json={"jobId": "12345", "jobStatus": "RUNNING"}, + request=httpx.Request("GET", "http://localhost:8080/job-info/12345"), + ) + session = RecordingSession(response=response) + sdk = self.create_client(session) + + self.assertTrue(sdk.jobs.job_exists(12345)) + + def test_job_exists_rejects_old_status_less_response(self): + response = httpx.Response( + 200, + json={"jobId": "12345"}, + request=httpx.Request("GET", "http://localhost:8080/job-info/12345"), + ) + session = RecordingSession(response=response) + sdk = self.create_client(session) + + self.assertFalse(sdk.jobs.job_exists(12345)) + + def test_job_exists_rejects_non_json_response(self): + response = httpx.Response( + 200, + text="<html>gateway error</html>", + headers={"Content-Type": "text/html"}, + request=httpx.Request("GET", "http://localhost:8080/job-info/12345"), + ) + session = RecordingSession(response=response) + sdk = self.create_client(session) + + with self.assertRaises(TypeError): + sdk.jobs.job_exists(12345) + def test_http_status_error_uses_response_message_and_preserves_cause(self): response = httpx.Response( 400,
