Skip to content

[improvement](job) Support immediate one-time S3 insert jobs - #70282

Open
freemandealer wants to merge 12 commits into
apache:masterfrom
freemandealer:task-neige-mr1924-base-mr1924-port
Open

freemandealer wants to merge 12 commits into
apache:masterfrom
freemandealer:task-neige-mr1924-base-mr1924-port

Conversation

@freemandealer

@freemandealer freemandealer commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Background

Scheduled INSERT jobs execute SQL through InsertTask and persist their task history. INSERT INTO s3(...) SELECT ... already supports external output, but job creation accepts only table INSERT commands.

What problem does this PR solve?

Issue Number: None
Related PR: None
PR Type: Enhancement

Problem Summary:

Allow an existing S3 INSERT to run as an immediate, one-time job. Validate its target, schedule, properties and query before registering the job, without deleting or writing destination files during validation. Route execution through InsertTask, handle cancellation and failures consistently, and mask TVF credentials in audit and job SQL displays. Most of the diff consists of tests for creation, execution, cancellation races, persistence and table-job compatibility.

Details

  • Change map: 440 changed production lines in 7 files and 2745 changed test lines in 12 files. Creation validation and SQL masking cover the supported job form. Task lifecycle, TVF execution and coordinator admission handle cancellation, completion and cleanup. The tests exercise those paths, persistence and existing table jobs.
  • Before and after: Wrapping a valid S3 INSERT in CREATE JOB ... ON SCHEDULE AT CURRENT_TIMESTAMP was rejected. It now creates an asynchronous one-time job. Recurring, delayed and STREAMING TVF jobs, and LOCAL/HDFS destinations, are rejected during creation.
  • Configs and defaults: No new configuration. Background tasks retain the default session timeout. Existing table INSERT jobs keep their schedules, label handling and execution path.
  • Impact on existing users: Table jobs retain their behavior. Direct TVF INSERTs also report timeout/backend failures correctly and participate in cancellation and credential masking. External output keeps its existing non-transactional semantics; cancellation or failure does not promise rollback of partial files.
  • Behavior change: The immediate S3 job form is supported; job creation performs validation without destination writes/deletions, and canceled task history is retained.

Example, using the same storage properties as a direct S3 INSERT:

CREATE JOB export_once ON SCHEDULE AT CURRENT_TIMESTAMP DO
INSERT INTO s3(
    "file_path" = "s3://example-bucket/export/result_",
    "format" = "csv",
    "s3.endpoint" = "https://s3.us-east-1.amazonaws.com",
    "s3.region" = "us-east-1",
    "s3.access_key" = "<access-key>",
    "s3.secret_key" = "<secret-key>"
)
SELECT * FROM source_table;

Testing

Earlier local validation on Linux x86_64 with ByteOpenJDK 17, as reported by the author:

  • Complete FE build through build.sh --fe -j 4, including packaging; UI built from the current lockfile.
  • FE Checkstyle: zero violations; git diff --check passed.
  • Native run-fe-ut.sh: 123 tests across nine classes, with zero failures, errors or skips. The 25 added tests cover validation without destination side effects, schedule/target rejection, SQL masking after serialization, timeout and backend errors, cancellation before/during planning and dispatch, resource cleanup, terminal callbacks, persistence, and table INSERT compatibility. The other 98 tests cover job status/configuration/authorization, existing INSERT context creation, SQL encryption, StmtExecutor cancellation and table-stream compatibility.

18 tests passed locally across InsertTaskLifecycleTest and InsertIntoTVFAdmissionCancellationTest, including both job cancellation entries. Removing only the pending-status check in Coordinator.enqueue made each entry exceed the five-second cancellation deadline with the only queue slot still occupied. Restoring the check let both return before that slot was released.

No external S3/MinIO end-to-end test was run in this checkout.

Notes for Reviewers

The TVF command uses master's existing sticky cancellation callback, so StmtExecutor needs no new special case. The current filesystem plugin path and external DML audit coordinator are preserved. The added tests use Mockito, including worker-local static/construction mocks, and restore the shared test environment after each case.

Release note

Support immediate, one-time jobs for INSERT INTO s3(...) SELECT ..., with destination credential masking and cancellation/error handling. Other TVF job schedules and LOCAL/HDFS job targets remain unsupported.

Check List (For Author)

  • Behavior changed: Yes (see Details).
  • Does this need documentation: Yes; follow-up website documentation should add the S3-only, immediate-only JOB form and its restrictions, using the example above.
  • Pre-submission status: Ready.

AI Disclosure

  • Tool: OpenAI Codex (GPT-6).
  • Generated: Conflict adaptations, migration of existing tests to Mockito, the job admission regression tests, and this description.
  • Human review: Not yet performed.

### Background

Scheduled INSERT jobs execute SQL through `InsertTask` and persist their task history. `INSERT INTO s3(...) SELECT ...` already supports external output, but job creation accepts only table INSERT commands.

### What problem does this PR solve?

Issue Number: None
Related PR: None
PR Type: Enhancement

Problem Summary:

Allow an existing S3 INSERT to run as an immediate, one-time job. Validate its target, schedule, properties and query before registering the job, without deleting or writing destination files during validation. Route execution through `InsertTask`, handle cancellation and failures consistently, and mask TVF credentials in audit and job SQL displays. Most of the diff consists of tests for creation, execution, cancellation races, persistence and table-job compatibility.

### Details

- **Change map:** 394 changed production lines in five files, plus 642 test lines in two files; no generated files or documentation files. Creation validation and SQL masking cover the supported job form; task lifecycle and TVF execution handle cancellation, completion and cleanup; the tests cover those paths and existing table jobs.
- **Before and after:** Wrapping a valid S3 INSERT in `CREATE JOB ... ON SCHEDULE AT CURRENT_TIMESTAMP` was rejected. It now creates an asynchronous one-time job. Recurring, delayed and STREAMING TVF jobs, and LOCAL/HDFS destinations, are rejected during creation.
- **Configs and defaults:** No new configuration. Background tasks retain the default session timeout. Existing table INSERT jobs keep their schedules, label handling and execution path.
- **Impact on existing users:** Table jobs retain their behavior. Direct TVF INSERTs also report timeout/backend failures correctly and participate in cancellation and credential masking. External output keeps its existing non-transactional semantics; cancellation or failure does not promise rollback of partial files.
- **Behavior change:** The immediate S3 job form is supported; job creation performs validation without destination writes/deletions, and canceled task history is retained.

Example, using the same storage properties as a direct S3 INSERT:

```sql
CREATE JOB export_once ON SCHEDULE AT CURRENT_TIMESTAMP DO
INSERT INTO s3(
    "file_path" = "s3://example-bucket/export/result_",
    "format" = "csv",
    "s3.endpoint" = "https://s3.us-east-1.amazonaws.com",
    "s3.region" = "us-east-1",
    "s3.access_key" = "<access-key>",
    "s3.secret_key" = "<secret-key>"
)
SELECT * FROM source_table;
```

### Testing

Locally on Linux x86_64 with ByteOpenJDK 17:

- Complete FE build through `build.sh --fe -j 4`, including packaging; UI built from the current lockfile.
- FE Checkstyle: zero violations; `git diff --check` passed.
- Native `run-fe-ut.sh`: 123 tests across nine classes, with zero failures, errors or skips. The 25 added tests cover validation without destination side effects, schedule/target rejection, SQL masking after serialization, timeout and backend errors, cancellation before/during planning and dispatch, resource cleanup, terminal callbacks, persistence, and table INSERT compatibility. The other 98 tests cover job status/configuration/authorization, existing INSERT context creation, SQL encryption, `StmtExecutor` cancellation and table-stream compatibility.

No external S3/MinIO end-to-end test was run in this checkout.

### Notes for Reviewers

The TVF command uses master's existing sticky cancellation callback, so `StmtExecutor` needs no new special case. The current filesystem plugin path and external DML audit coordinator are preserved. The added tests use Mockito, including worker-local static/construction mocks, and restore the shared test environment after each case.

### Release note

Support immediate, one-time jobs for `INSERT INTO s3(...) SELECT ...`, with destination credential masking and cancellation/error handling. Other TVF job schedules and LOCAL/HDFS job targets remain unsupported.

### Check List (For Author)

- Behavior changed: Yes (see Details).
- Does this need documentation: Yes; follow-up website documentation should add the S3-only, immediate-only JOB form and its restrictions, using the example above.
- Pre-submission status: Ready.

### AI Disclosure

- Tool: OpenAI Codex (GPT-6).
- Generated: Conflict adaptations, migration of the existing tests to Mockito, and this description.
- Human review: Not yet performed.
@hello-stephen

Copy link
Copy Markdown
Contributor

Thank you for your contribution to Apache Doris.
Don't know what should be done next? See How to process your PR.

Please clearly describe your PR:

  1. What problem was fixed (it's best to include specific error reporting information). How it was fixed.
  2. Which behaviors were modified. What was the previous behavior, what is it now, why was it modified, and what possible impacts might there be.
  3. What features were added. Why was this function added?
  4. Which code was refactored and why was this part of the code refactored?
  5. Which functions were optimized and what is the difference before and after the optimization?

@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@hello-stephen

Copy link
Copy Markdown
Contributor
TPC-H: Total hot run time: 28235 ms
machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
scripts: https://github.com/apache/doris/tree/master/tools/tpch-tools
Tpch sf100 test result on commit dbad5358efbad30af04f1c720a0f87d289879f74, data reload: false

------ Round 1 ----------------------------------
============================================
q1	17587	5140	5058	5058
q2	2141	303	242	242
q3	10251	1358	802	802
q4	4672	463	330	330
q5	7426	787	530	530
q6	181	186	151	151
q7	770	781	599	599
q8	9263	1305	1046	1046
q9	5463	4180	4186	4180
q10	6803	1287	1017	1017
q11	433	245	222	222
q12	635	392	270	270
q13	18091	3455	3020	3020
q14	275	272	259	259
q15	q16	724	718	666	666
q17	1180	739	562	562
q18	6998	6178	6094	6094
q19	1123	945	601	601
q20	370	321	225	225
q21	4898	2102	2241	2102
q22	333	290	259	259
Total cold run time: 99617 ms
Total hot run time: 28235 ms

----- Round 2, with runtime_filter_mode=off -----
============================================
q1	5605	5563	5596	5563
q2	678	587	520	520
q3	5159	5363	4897	4897
q4	1971	2145	1513	1513
q5	5246	5137	5371	5137
q6	253	210	158	158
q7	2420	2101	1905	1905
q8	2992	2678	2691	2678
q9	8022	7968	7944	7944
q10	3740	3649	3472	3472
q11	624	426	413	413
q12	697	675	513	513
q13	3598	3859	3290	3290
q14	295	318	307	307
q15	q16	752	727	659	659
q17	8207	7267	6858	6858
q18	12998	12177	12931	12177
q19	885	757	775	757
q20	2129	2139	1917	1917
q21	5603	4585	4636	4585
q22	488	482	424	424
Total cold run time: 72362 ms
Total hot run time: 65687 ms

@hello-stephen

Copy link
Copy Markdown
Contributor
TPC-DS: Total hot run time: 153262 ms
machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
scripts: https://github.com/apache/doris/tree/master/tools/tpcds-tools
TPC-DS sf100 test result on commit dbad5358efbad30af04f1c720a0f87d289879f74, data reload: false

query5	4315	581	440	440
query6	427	201	207	201
query7	4823	439	226	226
query8	315	167	155	155
query9	8814	3143	3155	3143
query10	476	308	248	248
query11	5986	3861	3579	3579
query12	146	93	89	89
query13	1238	434	330	330
query14	6068	3895	3629	3629
query14_1	3406	3379	3398	3379
query15	210	201	177	177
query16	948	421	414	414
query17	847	672	548	548
query18	2425	423	317	317
query19	196	179	148	148
query20	91	84	82	82
query21	213	126	106	106
query22	12989	12922	12822	12822
query23	13443	12799	12349	12349
query23_1	12508	12523	12435	12435
query24	7384	829	473	473
query24_1	478	481	465	465
query25	536	455	386	386
query26	1251	254	143	143
query27	2781	438	275	275
query28	4618	2019	2011	2011
query29	1545	603	464	464
query30	305	216	186	186
query31	1015	933	818	818
query32	146	88	94	88
query33	524	302	243	243
query34	885	851	492	492
query35	728	750	650	650
query36	816	816	708	708
query37	124	101	84	84
query38	1754	1740	1691	1691
query39	795	799	745	745
query39_1	749	726	740	726
query40	226	123	101	101
query41	71	69	67	67
query42	99	83	82	82
query43	344	358	311	311
query44	1320	702	705	702
query45	183	173	167	167
query46	824	984	577	577
query47	2950	2958	2748	2748
query48	297	312	220	220
query49	575	389	292	292
query50	685	271	210	210
query51	10746	10652	10422	10422
query52	82	77	67	67
query53	183	209	149	149
query54	243	190	194	190
query55	76	71	61	61
query56	226	218	207	207
query57	1644	1616	1564	1564
query58	286	245	254	245
query59	2088	2227	1946	1946
query60	303	241	224	224
query61	148	138	151	138
query62	373	339	306	306
query63	185	160	162	160
query64	2735	973	778	778
query65	3317	3283	3256	3256
query66	1767	419	308	308
query67	22537	22553	22520	22520
query68	2968	1000	613	613
query69	379	310	249	249
query70	837	773	781	773
query71	296	229	215	215
query72	2701	2554	2240	2240
query73	513	521	292	292
query74	4635	4488	4330	4330
query75	2362	2280	1899	1899
query76	2319	1021	586	586
query77	357	371	266	266
query78	9681	9689	9139	9139
query79	978	850	535	535
query80	1269	420	351	351
query81	578	312	275	275
query82	573	134	104	104
query83	299	192	183	183
query84	307	117	104	104
query85	849	424	368	368
query86	411	242	236	236
query87	1980	1931	1809	1809
query88	3813	2775	2753	2753
query89	341	281	242	242
query90	1872	171	155	155
query91	162	155	128	128
query92	98	86	87	86
query93	1107	993	572	572
query94	627	307	273	273
query95	569	325	305	305
query96	692	486	244	244
query97	2439	2434	2300	2300
query98	173	150	150	150
query99	777	759	660	660
Total cold run time: 237563 ms
Total hot run time: 153262 ms

@hello-stephen

Copy link
Copy Markdown
Contributor
ClickBench: Total hot run time: 24.17 s
machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
scripts: https://github.com/apache/doris/tree/master/tools/clickbench-tools
ClickBench test result on commit dbad5358efbad30af04f1c720a0f87d289879f74, data reload: false

query1	0.01	0.01	0.01
query2	0.09	0.04	0.04
query3	0.26	0.08	0.08
query4	1.60	0.10	0.09
query5	0.24	0.25	0.24
query6	1.18	0.68	0.67
query7	0.04	0.01	0.01
query8	0.05	0.04	0.03
query9	0.43	0.36	0.36
query10	0.60	0.59	0.60
query11	0.20	0.15	0.14
query12	0.18	0.15	0.16
query13	0.49	0.48	0.50
query14	1.03	1.00	1.01
query15	0.63	0.60	0.60
query16	0.36	0.36	0.35
query17	1.15	1.11	1.10
query18	0.20	0.19	0.19
query19	2.09	1.95	1.94
query20	0.02	0.02	0.01
query21	15.48	0.18	0.12
query22	4.78	0.05	0.05
query23	16.29	0.32	0.12
query24	3.05	0.57	0.41
query25	0.10	0.07	0.06
query26	1.25	0.22	0.16
query27	0.05	0.05	0.03
query28	4.04	0.85	0.37
query29	12.52	4.15	3.20
query30	0.28	0.12	0.09
query31	2.77	0.56	0.33
query32	3.21	0.59	0.50
query33	3.16	3.15	3.18
query34	15.25	4.00	3.40
query35	3.36	3.30	3.31
query36	0.55	0.49	0.44
query37	0.09	0.06	0.06
query38	0.05	0.04	0.04
query39	0.04	0.03	0.03
query40	0.18	0.14	0.15
query41	0.09	0.03	0.03
query42	0.04	0.03	0.03
query43	0.04	0.03	0.03
Total cold run time: 97.52 s
Total hot run time: 24.17 s

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of PR 70282 at head dbad535 found two blocking lifecycle defects in the new INSERT JOB execution path:

  • InsertTask.runTask removes the worker ConnectContext before TaskProcessor.closeTaskContext runs. The outer cleanup therefore cannot unregister the query or close StatementContext and its connector scope after success, failure, or cancellation.
  • The new INSERT INTO TVF task branch constructs a parsed StmtExecutor without binding it to ConnectContext. External source scans consequently skip split cancellation and connector task-group registration; cancellation during planning before coordinator publication can leave scan/query-finish resources without the command's coordinator cleanup.

I traced coordinator publication, cancellation callbacks, the execution lock around file deletion and dispatch, timeout/error handling, query registration, Nereids planning cleanup, parser and validation rules, audit masking, terminal state transitions, journal/replay behavior, and the changed tests. No additional actionable issue was found. The user focus file contains no extra focus points. No prior inline review comments or blocking findings exist, so existing_blocking_comment_ids is empty. This was a static review only; no build or test execution was performed. The review converged after two rounds, with all assigned reviewers returning NO_NEW_VALUABLE_FINDINGS in the final round.

Review converged after 2 round(s).

@hello-stephen

Copy link
Copy Markdown
Contributor

FE UT Coverage Report

Increment line coverage 86.06% (142/165) 🎉
Increment coverage report
Complete coverage report

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Codex automated review failed and did not complete.

Error: Review setup stopped before context preparation ran; inspect the first failed or cancelled setup step.
Workflow run: https://github.com/apache/doris/actions/runs/42569808466

Please inspect the workflow logs and rerun the review after the underlying issue is resolved.

@freemandealer

Copy link
Copy Markdown
Member Author

run p0

@freemandealer

Copy link
Copy Markdown
Member Author

run cloud_p0

### Background

INSERT JOB tasks run commands directly on reusable task workers. Planning can register scans and connector work before a coordinator is published.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (follow-up)
PR Type: Bugfix

Problem Summary:

INSERT tasks removed their worker context before TaskProcessor could close it, and parsed executors were not bound to the context during planning. Keep cleanup with the worker, bind the executor before planning, and reuse query finalization to release scans, connector scopes, and callbacks on every task outcome.

### Details

- **Change map:** 25 changed lines in production code and 339 in tests; no generated files or environment changes are committed.
- **Frequency:** Every initialized INSERT task could skip outer context cleanup; cancellation during planning exposes the missing executor binding.
- **Root cause:** InsertTask removed the thread-local before TaskProcessor read it. The parsed StmtExecutor constructor does not bind itself, and direct command execution bypasses StmtExecutor.execute() finalization.
- **Why existing tests missed it:** The insert fixture overrode runTask, lifecycle tests invoked tasks directly and expected early context removal, and TVF helpers bound executors manually.
- **Fix:** Retain the context until TaskProcessor finalizes the executor and closes the statement, including the initialization fallback and cleanup failures. Bind parsed executors before commands start planning.
- **Other paths and branches:** Keep table INSERT labels, runWithUpdateInfo, scheduling, persistence, and terminal transitions. Reuse the existing scan, connector task group, and query callback owners.
- **Behavior change:** Planning cancellation stops registered scans and connector work before coordinator publication, while final cleanup stays on the execution worker.

### Testing

- Native run-fe-ut.sh with InsertTaskLifecycleTest,InsertIntoTVFJobTest,TaskProcessorTest,StmtExecutorTest: 91 tests, 0 failures, 0 errors, 0 skipped.
- Restore the two production files from dbad535 and run the final tests: 91 tests, 10 failures, 3 errors, 0 skipped. Failures show missing statement cleanup, leaked scopes, and a null planning executor.
- build.sh --fe -j 4 through the doris-compile wrapper: passed, including Checkstyle and the native UI build.
- FE core checkstyle:check: passed with 0 violations. git diff --check: passed.
- Coverage includes real TaskProcessor worker reuse, initialization and execution failures, cancellation before coordinator publication, late work registration, callbacks, and cleanup exceptions.

### Release note

INSERT JOB tasks release query and connector resources on success, failure, and cancellation. Cancellation during planning stops registered scan work before a coordinator exists.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Ready

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: Production changes, regression tests, and this description.
- Human review: Pending independent review; agent self-review is recorded in output/pr-70282/fix-notes.md.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

…ests

### Background

Immediate one-time S3 INSERT jobs use the TVF command and task-worker lifecycle.
Current master collects audit participants through the executor's standard coordinator.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (updated PR), apache#70545 (unified audit coordinator)
PR Type: Bugfix

Problem Summary:

Merge current master while preserving the INSERT JOB cancellation and cleanup paths.
Resolve the TVF execution conflict and retain the closed coordinator for audit participant lookup.
Also keep independent manifests in two Iceberg cancellation fixtures so large SDK worker pools
do not trigger automatic manifest merging before their cancellation assertions.

### Details

- **Change map:** Most changes in this merge come from upstream master. Manual resolution
  beyond the automatic merge affects one production file and three test files (+13/-58);
  no environment configuration or generated artifacts are included.
- **Frequency:** The TVF conflict occurs with master's unified audit API. The Iceberg
  fixture fails when its independent-manifest count crosses the SDK merge threshold.
- **Root cause:** The previous TVF command referenced a removed audit setter and cleared
  the standard coordinator before audit collection. The fixtures did not disable manifest merging.
- **Why existing tests missed it:** Previous focused validation predated the upstream audit
  change and did not execute the worker-count-sensitive Iceberg suite.
- **Fix:** Retain the existing cancellation handshake, unregister and close resources,
  retain the standard audit reference, and disable merging only in the two test fixtures.
- **Other paths and branches:** Direct TVF execution and background jobs retain their
  respective tests; the same fixture correction is being handled separately for apache#70142.
- **Behavior change:** Preserve audit participants for successful and failed TVF jobs;
  no production Iceberg behavior or global setting changes.

### Testing

- Local standard FE build and Checkstyle passed.
- 106 lifecycle and audit tests passed, with negative controls reproducing compilation
  failure and ten audit-ownership failures before the corresponding corrections.
- All 253 IcebergScanPlanProviderTest cases passed, including the three formerly failing branches.
- An independent review of the TVF adaptation passed. The fixture patch was separately reviewed.
- A full native FE UT attempt reached 14,442 reported tests before its two-hour timeout;
  seven observed failures depended on the host timezone. The six affected classes were
  rerun with Asia/Shanghai without source changes: 58 tests passed, zero skips.
- The full suite remains incomplete. Remote TeamCity results have not been confirmed;
  its logs required authentication.

### Notes for Reviewers

This is an ordinary fast-forward update of the PR branch by a merge commit whose parents
are the previous PR head and the tested master revision. Its tree exactly matches the
accepted local candidate. Existing PR commits are retained.

### Release note

Preserve backend audit participants for immediate one-time S3 INSERT jobs after execution.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: complete FE UT exceeded the local time limit;
  remote CI and its required review have not been confirmed.

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: Conflict resolution, test fixture correction, validation scripts, and this description
- Human review: Not yet performed; an independent automated code review passed.
freemandealer added a commit to freemandealer/doris that referenced this pull request Nov 17, 2026
### Background

Iceberg SDK cancellation tests create more independent manifests than SDK workers
so they can verify that cancellation stops queued readers and joins active readers.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70142 (updated PR), apache#70282 (same fixture correction)
PR Type: Test

Problem Summary:

Automatic manifest merging can collapse the fixtures before their cancellation assertions
run on machines with larger worker pools. Explicitly disable manifest merging for the two
test tables while preserving all existing cancellation, reader-join and healthy-scan assertions.
There are no production changes or changes to Export history and label ownership.

### Details

- **Failure:** The fixtures expected 131 independent manifests but observed 32 before cancellation.
- **Cause:** The SDK enables manifest merging by default at 100 manifests, while the fixtures
  create 2 * worker-count + 3 manifests without disabling that behavior.
- **Stability evidence:** The complete original-branch IcebergScanPlanProviderTest passed
  all 243 cases, including both data branches and the delete-manifest cancellation case.
  The five Export test classes retained and passed all 31 cases.

### Testing

The repository-native run-fe-ut.sh selected the complete IcebergScanPlanProviderTest and
ExportHistoryPersistenceTest, ExportHistoryRetentionTest, loadv2.ExportMgrTest, ExportJobTest
and ExportOutfileInfoTest: 274 tests, zero failures, errors or skips. Checkstyle ran with
checkstyle.skip=false and reported no violations. One initial clean rebuilt the branch's
local Maven output; shared caches and source configuration were unchanged.
TZ=Asia/Shanghai and the FE JVM timezone were set only in the test process.
No full FE suite or remote CI result is claimed.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: selected unit tests and Checkstyle passed;
  the full FE suite and remote CI have not been verified for this update.

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: Two test-table properties, explanatory comments, verification scripts and this description
- Human review: Not yet performed; the patch and raw test evidence were independently checked by the planner.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of PR #70282 at 09e46df9819dadcc791cd94faa3daa7c1b2eb8a9: no new actionable findings. All 11 changed files and their relevant caller, scheduler, cancellation, cleanup, display and replay paths were inspected.

Both existing P1 findings are addressed at this head: 4480623182 is covered by binding the task executor before planning and closing query/scan scope; 4480622802 is covered by retaining the worker context until TaskProcessor finalizes the executor and closes StatementContext. Neither remains an existing blocker, and neither is reposted.

Reviewed execution flow: CREATE JOB -> schedule/target/query validation without destination deletion or dispatch -> persisted InsertJob -> TaskProcessor -> InsertTask -> TVF planning/coordinator -> destination preparation/fragment dispatch -> join/status -> task terminal history -> executor/statement cleanup.

Critical checkpoint conclusions:

Checkpoint Conclusion from static inspection
Goal and supporting tests Immediate one-time S3 INSERT jobs are accepted; unsupported schedules and LOCAL/HDFS job targets are rejected. Added unit tests cover these routes.
Scope and clarity Six production files implement validation, execution, display and shared cleanup; five test files cover these changes or stabilize cancellation fixtures. Changes are focused.
Concurrency, critical variables and locks The task monitor serializes initialization and terminal transitions; captured local handles survive cancellation. Atomic cancellation and a volatile coordinator connect worker/cancel threads. The dedicated execution lock serializes destination side effects/dispatch with cancellation acknowledgment; queue cancellation precedes waiting for that lock. No reachable lock inversion was substantiated.
Lifecycle and resource ownership The bound executor owns planning-time scans and callbacks. Command cleanup closes its coordinator; TaskProcessor finalizes query scope and closes StatementContext before removing the worker thread-local, including failure paths.
Configuration and dynamic changes No configuration is added or changed. Background jobs retain the existing fresh-session timeout behavior.
Function/storage compatibility and rolling upgrades No stored schema, function symbol or FE/BE wire format is changed; existing job serialization/replay paths are reused. The feature uses the new FE execution path.
Thrift/protobuf definitions No gensrc files or field/enum IDs change.
Parallel paths Table INSERT retains labels and runWithUpdateInfo; streaming job creation remains separate. Direct TVF INSERT shares the corrected error/cancellation handling.
Special conditions S3-only and immediate-only restrictions match the supported job scope. Ordinary INSERT jobs cannot change their SQL through streaming-only ALTER JOB.
Test coverage Inspected positive/negative validation, masking roundtrip, persistence, timeout/backend errors, cancellation before/during planning and dispatch, terminal callbacks, cleanup, worker reuse and table/streaming compatibility tests. Real storage end-to-end behavior remains unexecuted.
Test result artifacts No expected-result output files are changed. Added/adjusted JUnit assertions and manifest fixtures match the intended control flow.
Observability Existing job/task status, finish time, errors and job/task identifiers cover the new path; display SQL is masked and the task error log omits raw SQL. No new metric was found necessary for this scope.
Transactions, persistence and failover Task history and terminal job states use existing serialized queues and update logs. Replay restores that metadata and recomputes the unpersisted display mask. No new transactional protocol is introduced.
Data writes, atomicity and crashes S3 output retains existing non-transactional external-write behavior: cancellation, failure or FE/BE crash may leave partial output; rollback is not promised. CREATE validation does not delete destination files or dispatch a coordinator.
FE/BE variable propagation No new cross-process variables are introduced. Existing coordinator and filesystem paths are reused.
Complexity and performance No new per-row work or unbounded retry/scan was introduced; display masking is cached after successful computation.
Other concerns Further checks of pre-coordinator failure, late resource registration, duplicate terminal callbacks and alternate task producers produced no additional verified bug.

User focus: no additional focus points were supplied. The complete PR was reviewed, including the two existing lifecycle concerns.

Validation limits: static inspection only. No builds, tests, benchmarks, S3/MinIO end-to-end execution or runtime race reproduction were performed by this review. No unresolved static candidate or changed-file coverage gap remains. Review converged in 2 rounds.

Review converged after 2 round(s).

### Background

Scheduled INSERT jobs parse their DO body before registration. Table INSERT and immediate one-time S3 TVF INSERT have separate validation paths; unsupported commands are rejected with an AnalysisException.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (changed the unsupported-command error prefix)
PR Type: Bugfix

Problem Summary:

CREATE JOB ... DO UPDATE is still rejected, but its changed diagnostic no longer contains the prefix required by the existing JOB regression assertion. Restore the legacy prefix while keeping the command class diagnostic and avoiding the original SQL in the message. Add a real FE command execution test for this contract.

### Details

- **Frequency:** Every unsupported scheduled INSERT JOB body that reaches command validation, including UPDATE.
- **Root cause:** The unsupported-command diagnostic replaced the established "Not support this sql :" prefix with "Unsupported INSERT JOB command:".
- **Why existing tests missed it:** Existing FE table/TVF job tests did not assert the legacy prefix; the existing Groovy regression assertion exposed the contract mismatch.
- **Fix:** Change only the error prefix and retain the parsed command class name, exception type, cause, and rejection behavior without adding the SQL text.
- **Other paths and branches:** Table INSERT, S3 TVF validation, and scheduling restrictions keep their existing logic. No Groovy assertions or golden results change.
- **Behavior change:** Unsupported INSERT JOB diagnostics again contain the legacy prefix.

### Testing

- Before the production change, run the new CreateJobRegressionContractTest through bash run-fe-ut.sh --run on the target baseline: 1 test, 1 expected legacy-prefix assertion failure, 0 errors, 0 skipped, native Maven exit 1. Native console/XML and the test source hash are archived.
- The delivery gate runs CreateJobRegressionContractTest, InsertIntoTVFJobTest, and InsertTaskLifecycleTest together through the native FEUT entry point, with Checkstyle enabled and the build cache disabled. It requires fresh XML for all three classes, an executed new contract test, zero failures/errors/skips, native exit 0, and the unchanged negative-control test source hash.
- The source-whitespace gate checks the complete diff against the target baseline with git diff --check.
- Full SQL regression, full FEUT, external S3/BE execution, and remote CI attribution are unverified.

### Release note

Unsupported INSERT JOB error messages preserve the established prefix and retain the command class diagnostic without echoing the original SQL.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: focused native FEUT and Checkstyle are the delivery gate; full SQL regression and remote CI attribution remain unverified.

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: The production message change, FE test, local verification artifacts, and this description.
- Human review: Pending independent review.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of PR #70282 at 2d0f9017a6308462f9419572aee5388a73636e1d found one new P2 regression: canceling one server-prepared TVF INSERT leaves its retained command permanently canceled, so later EXECUTEs on that handle fail before planning. The inline comment describes the trigger and fix direction. All 12 changed files and their relevant upstream/downstream paths were inspected.

Both prior P1 findings are addressed at this head. 4480623182 is covered by binding the parsed executor before task planning and finalizing owned scan/query work. 4480622802 is covered by retaining the worker ConnectContext until TaskProcessor finalizes the executor, closes StatementContext, and removes the thread-local. Neither remains an existing blocker or is reposted.

The inspected execution flow is:

CREATE JOB -> schedule/target/query validation -> persisted InsertJob
  -> TaskProcessor -> InsertTask -> TVF plan/coordinator
  -> destination preparation/fragment dispatch -> join/status
  -> terminal task history -> executor/statement cleanup

PREPARE -> retained TVF command -> EXECUTE -> cancel sets command flag
  -> next EXECUTE reuses command -> immediate cancellation error [P2]

Critical checkpoint conclusions:

Checkpoint Conclusion from static inspection
Goal and supporting tests Immediate ONE_TIME S3 INSERT jobs are accepted; delayed, recurring, STREAMING and LOCAL/HDFS TVF jobs are rejected. Added unit tests cover these creation and execution routes. Prepared reuse needs the inline fix.
Scope and clarity Six production files reuse existing job, planner, masking and cleanup facilities; six test files cover behavior or preserve cancellation-fixture intent. Changes are focused.
Concurrency, variables and locks The task monitor guards initialization and terminal transitions; local handles survive cancellation. Atomic cancellation and the volatile coordinator connect worker/cancel threads. executionLock serializes destination deletion/dispatch with cancellation acknowledgment; coordinator cancellation wakes workload admission before waiting for that lock. No reachable lock inversion was substantiated.
Lifecycle and ownership Executor binding and worker-context retention repair the previous P1s; coordinator and statement/scan scopes have explicit cleanup paths. The new canceled flag outlives one prepared execution, producing the P2 finding. No C++ static initialization applies.
Configuration and dynamic behavior No configuration is added or changed. Background tasks retain fresh-session timeout defaults.
Function/storage compatibility and rolling upgrades No function symbol, persisted-field schema or FE/BE wire format changes. Existing job/task serialization and replay are reused; executing the new feature requires a supporting FE.
Thrift/protobuf IDs No gensrc definitions, field IDs or enum values change.
Parallel paths Table INSERT keeps labels, job IDs and runWithUpdateInfo; streaming creation remains separate. Direct TVF execution shares corrected timeout/error/cancel handling. Server-prepared command reuse exposes the new P2. Shared TaskProcessor cleanup was also traced through MTMV.
Special conditions S3-only/immediate-only checks match supported scope. join(false), incomplete completion and non-OK backend status fail explicitly. SQL display masking fails closed and shared rewriting converts parser code-point endpoints.
Test coverage Inspected validation, masking roundtrip, persistence, initialization failure, timeout/backend/dispatch failure, cancellation during planning/publication/dispatch/join, late registration, terminal callbacks, worker reuse and table/streaming compatibility tests. Prepared cancel-then-execute coverage is missing. No real S3 end-to-end behavior was verified.
Test result artifacts No .out files change. New/adjusted Java assertions and Iceberg manifest fixtures match the intended control flow; test execution was not performed.
Observability Existing task/job status, finish time, errors and identifiers cover the new path. Display SQL is masked and task error logging omits raw SQL. No additional metric was found necessary for this scope.
Transactions, persistence and failover Existing serialized task history and callback/update-log paths retain terminal state; cancellation adds an update after its transition. Existing replay restores nonstreaming job metadata. No new transaction protocol is introduced; runtime failover was not tested.
Data writes, atomicity and crashes CREATE validation does not delete destination files or dispatch fragments. Output retains existing nontransactional external-write semantics: cancellation, failure or FE/BE crash can leave partial files. No rowset visibility or delete-bitmap logic changes.
FE/BE variable propagation No new cross-process variable; existing physical sink/coordinator/filesystem payloads are reused.
Complexity and performance No new per-row loop, unbounded retry or material common-case regression identified. Display masking is cached; the extra cancellation update duplicates a manager-level update on a rare operation.
Other concerns and risk disposition Validation/source-resource ownership and Unicode/CTE masking risks were dismissed with code evidence. A speculative multi-task INSTANT lock cycle has no current production multi-plan creator. Every candidate was accepted, deduplicated or dismissed; no unresolved static candidate or changed-file coverage gap remains.

User focus: no additional focus points were supplied. The whole PR and both prior lifecycle concerns were reviewed.

The review converged after two rounds: all three assigned reviewers returned NO_NEW_VALUABLE_FINDINGS in the latest round, and the final changed-file/candidate/risk/anchor sweep is complete. Convergence means the bounded review is complete; the reported P2 still needs correction.

Validation limits: static inspection only. No builds, tests, benchmarks, S3/MinIO end-to-end execution, runtime race reproduction or FE failover checks were run by this review.

Review converged after 2 round(s).

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of all 13 changed files at ca9ef94. One new P2 finding: cancellation can miss publication of a workload admission token and then wait behind the dispatch lock until admission or timeout.

Existing review dispositions: 4480623182 (executor binding before planning), 4480622802 (worker context cleanup), and 4609912404 (prepared cancellation state) are addressed by this head. No previously reported P0/P1 finding remains applicable; none is duplicated.

Critical checkpoint conclusions:

Checkpoint Conclusion
Goal and proving tests Immediate one-time S3 jobs are routed through InsertTask; creation rejects unsupported schedules/targets and plans without destination deletion or dispatch. Unit tests cover intended behavior; the admission-token cancellation race remains.
Scope and reuse Six production files reuse the existing planner, job scheduler, persistence and masking machinery. The related lifecycle fixes and test fixture changes are focused.
Concurrency and shared state Worker versus cancellation threads share task state under the task monitor; each TVF run owns its callback state and coordinator reference. M1 identifies the admission publication gap.
Work under locks and lock order No reverse task-monitor acquisition was found in dispatch/cleanup. Holding executionLock across admission makes the missed-token race stall cancellation; see the inline finding.
Lifecycle and memory ownership Executor finalization, query-finish callbacks and StatementContext closure cover task completion/failure/planning cancellation; execution retains local handles after task cancellation. Prepared callbacks retain only their execution. No C++ static initialization or BE memory ownership changes.
Configuration and dynamic changes No configuration item is added. Background tasks keep existing fresh-session defaults.
Compatibility and rolling upgrades No persisted field, public plugin API, storage format or wire schema is changed; existing job serialization/replay is reused.
Thrift/protobuf IDs No gensrc/thrift or gensrc/proto changes.
Parallel paths Direct and prepared TVF execution, scheduled/table/INSTANT inserts, streaming-job creation and shared MTMV cleanup were inspected; no additional new defect was established.
Conditional checks S3-only, ONE_TIME/immediate, terminal-state and cancellation guards have concrete supported/unsupported cases and corresponding tests.
Test coverage Inspected success, failure, timeout, planning/dispatch cancellation, prepared reuse, worker reuse, persistence, masking and table compatibility tests. Real admission-token publication is untested because the TVF tests mock Coordinator.exec; add a deterministic saturated-queue interleaving case for M1.
Changed expected results No regression .out/result artifact changes. Iceberg fixtures disable manifest merging to preserve queued independent manifests.
Observability Job/task identifiers remain in diagnostics, raw SQL is removed from task failure logging, and display masking fails closed. No additional metric gap was established.
Transactions, persistence and failover Cancellation now logs after terminal task/job updates; success/failure use existing EditLog and replay paths. Internal transaction, visible-version and delete-bitmap logic are unchanged. Existing scheduler recovery semantics are reused.
Data writes and atomicity S3 output retains existing nontransactional behavior: failure/cancellation can leave partial files. CREATE validation does not perform destination deletion/writes. No rollback guarantee is introduced.
FE-to-BE variables No new transmitted field or session variable.
Performance Display SQL masking is cached; no new hot-loop or unbounded collection regression was established. The cancellation wait is the concrete latency issue.
Other concerns and user focus No additional user-provided focus. All initial risk items and candidates have explicit dispositions; no other verified finding or unresolved code question remains.

Validation was static inspection only: no builds, tests, benchmarks, submodule initialization, source edits, or S3/MinIO execution were performed. Runtime behavior and external service integration therefore remain unvalidated. Review convergence concerns coverage and disposition of findings, not absence of bugs.

Review converged after 2 round(s).

// Wake a Coordinator that is waiting for workload admission during exec().
coordinator.cancel(new Status(TStatusCode.CANCELLED, "Insert into TVF canceled"));
}
synchronized (executionLock) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Honor cancellation when publishing the admission token. With a saturated workload group, cancellation can run after Coordinator.shouldQueue() returns true but before setQueueInfo(). The first coordinator.cancel() sees no token; exec() then publishes a waiting token and blocks in QueueToken.get() while holding executionLock. This synchronized block prevents the second cancel (and StmtExecutor.cancel's remaining cleanup) from waking that token until admission or the full queue/query timeout. Consequently CANCEL JOB TASK and STOP's cancel(false) can block for that timeout while holding the task monitor. Make token publication honor pending cancellation or move the admission wait outside this lock, and cover cancellation before token publication.

### Background

Workload admission gives each queued query a token. The coordinator publishes that token so cancellation can wake the query while it waits for a slot.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (TVF insert cancellation)
PR Type: Bugfix

Problem Summary: A TVF insert can retain a cancellation reason just before its admission token becomes visible. Its cancellation callback then waits for dispatch to leave the startup lock while dispatch waits for an admission slot. Recheck the retained status immediately after publishing the token so a canceled query can leave the queue while another query still holds the slot.

### Details

- **Frequency:** Requires a query entering admission concurrently with cancellation. The delay is visible when the queue is saturated.
- **Root cause:** The first cancel can find no token after the execution thread has passed its early cancellation check.
- **Why existing tests missed it:** They covered cancellation around fragment dispatch and retention of queue error reasons without pausing a real saturated queue between token allocation and publication.
- **Fix:** Cancel the newly published token if the retained status is non-OK, then use the existing token wait and error handling. Coordinator close owns the token release.
- **Other paths and branches:** Cancellation following publication finds the token through the existing coordinator callback. Normal admission and the status check before fragment dispatch retain their existing behavior.
- **Behavior change:** A queued query that has already been canceled or timed out can return promptly with its retained reason.

### Testing

The new InsertIntoTVFAdmissionCancellationTest exercises a real TVF command, coordinator and single-slot workload queue. On the original code its bounded waits fail for TVF cancellation and a TIMEOUT recorded before publication. It also covers immediate admission with a retained TIMEOUT, cancellation after publication, and dispatch of a healthy waiter to the mocked backend.

The local verification gate runs the same test with CoordinatorTest, InsertIntoTVFJobTest, InsertIntoTVFPreparedExecutionTest, InsertIntoTVFCommandTest, InsertTaskLifecycleTest and TaskProcessorTest through run-fe-ut.sh. It requires fresh passing XML for each class, Checkstyle coverage of both changed files and a clean whitespace check.

### Release note

Canceling a query as it enters a saturated workload queue now returns promptly with the original reason.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: verification covers focused FE tests with a mocked backend.

### AI Disclosure

- Tool: OpenAI Codex (GPT-6)
- Generated: The production fix, regression tests and this description.
- Human review: Pending.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of head 55a3b01d27ba897e652a292648140c6b536c3915 completed. No new verified findings. The review converged in one round: both complete-scope reviewers and the separate cancellation-risk reviewer returned NO_NEW_VALUABLE_FINDINGS; all changed files, candidate dispositions, and risk items were checked.

Existing findings were independently rechecked and are addressed at this head: executor binding (4480623182), worker context cleanup (4480622802), prepared-execution cancellation isolation (4609912404), and cancellation before admission-token publication (4610944383). Neither existing P1 remains applicable; no duplicate inline comments are submitted.

Critical checkpoint conclusions:

  1. Goal and proof: immediate, one-time S3 INSERT jobs are supported; delayed/recurring/STREAMING TVF jobs and LOCAL/HDFS job destinations are rejected. Added unit tests cover creation validation, execution outcomes and cancellation; their code was inspected only.
  2. Scope and reuse: creation reuses TVF planning, execution reuses existing commands, and cleanup reuses executor/statement scopes. The Iceberg changes keep independent manifests available for cancellation fixtures.
  3. Concurrency: traced worker versus cancel-command threads, task monitor, per-execution lock, Coordinator status lock and admission token. Planning/execution occur outside the task monitor; deletion/dispatch deliberately synchronize cancellation acknowledgement. No additional lock cycle or lost-publication scenario was established.
  4. Lifecycle: local execution handles survive cancellation, terminal callbacks serialize, and worker finalization closes query/statement resources, including failures before Coordinator creation. Prepared commands allocate independent cancellation state per run. No static-initialization changes.
  5. Configuration: no new settings; background tasks retain fresh-session timeout defaults.
  6. Compatibility: inspected scheduled table jobs, direct/prepared TVF statements and shared task cleanup. No incompatible persisted format or plugin interface change identified; new job SQL requires supporting FE code.
  7. Thrift/protobuf: no definition or field-ID changes.
  8. Parallel paths: table/bulk/streaming jobs, CREATE/ALTER masking, both job display paths and prepared reuse were traced; no additional verified regression found.
  9. Conditions and errors: target/schedule/terminal guards correspond to reachable cases; timeout, failed backend and upload/dispatch failure propagate as failures. Creation validation does not delete or write destination files.
  10. Tests: negative validation, latch-based planning/dispatch/admission races, late callbacks, worker reuse, cleanup failures and serialization are covered by inspected unit tests. No S3/MinIO end-to-end test was added or executed here.
  11. Test results: no regression output files changed; inspected Java expectations match the traced control flow. No passing runtime result is claimed.
  12. Observability: task/query identifiers, terminal status, error and timestamps remain available. SQL display/audit masking covers destination properties and avoids raw-SQL task logging.
  13. Persistence and failover: cancellation uses existing task fields and full-job journal/replay; no new transaction protocol. External output retains its existing nontransactional crash/failure semantics.
  14. Writes and atomicity: no table visibility/version/delete-bitmap changes. Cancellation or failure can leave partial external files; rollback or exactly-once output is not promised.
  15. FE/BE propagation: no new wire variables.
  16. Performance: no new unbounded loop, material hot-path complexity increase or substantiated performance regression identified; display masking is cached.
  17. Final recheck: all 15 changed files and the upstream/downstream paths were covered, including late cancellation, ready tokens, initialization failure, validation resources and masking boundaries. No unresolved static candidate remains.

No additional user-provided focus was supplied. This was static inspection only: no builds, tests, benchmarks, source changes or external storage execution. Runtime behavior remains unvalidated by this review.

Review converged after 1 round(s).

### Background

INSERT JOB metadata and SHOW output lazily mask the persisted execution SQL. The display cache is omitted from Gson persistence and must be rebuilt after recovery, including on metadata threads without a ConnectContext.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (related INSERT INTO TVF JOB support)
PR Type: Bugfix

Problem Summary:

Valid ordinary-table INSERT JOB SQL can display as <redacted> when masking runs without a thread session. Traverse the source query and leading CTEs for masking without constructing an execution table sink. Keep property masking, execution SQL and persistence unchanged.

### Details

- **Frequency:** A display cache miss on a sessionless metadata thread, including after Gson recovery.
- **Root cause:** The encryption builder inherited ordinary INSERT sink construction, which unconditionally reads the current session variables.
- **Why existing tests missed it:** Existing TVF JOB masking checks ran with a bound session and did not assert exact ordinary VALUES text after sessionless recovery.
- **Fix:** Override the encryption visitor for ordinary INSERT to visit leading CTE queries and the INSERT source, reusing existing TVF property replacement.
- **Other paths and branches:** TVF target masking and the normal execution parser remain unchanged. Audit and streaming callers use replacement spans rather than the returned masking plan. Only the current branch is covered.
- **Behavior change:** Ordinary VALUES/SELECT display remains intact; S3 properties stay masked and malformed SQL stays redacted.

### Testing

- Frozen regression: native run-fe-ut.sh --run with InsertJobDisplaySqlTest#freshValuesWithoutContext+restoredValuesWithoutContext on unchanged production: all six cases failed at the expected VALUES SQL versus <redacted> assertion (zero errors/skips).
- Delivery gate: native run-fe-ut.sh --run for InsertJobDisplaySqlTest, AuditEncryptionSessionVariableTest, RepositoryAuditEncryptionTest, EncryptSQLTest and InsertIntoTVFJobTest, with Checkstyle enabled and fresh XML/source fingerprints checked.
- No real BE/S3 execution or full SQL regression run.

### Release note

Fix ordinary INSERT JOB SQL displaying as <redacted> on metadata queries after restart when no session is bound, while retaining masking of sensitive properties.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: native FEUT/Checkstyle gate required; real BE/S3 and full SQL regression not run.

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: Code, regression tests and this description.
- Human review: Pending independent review.
### Background

INSERT JOB display and audit SQL use the encryption parser to collect sensitive property ranges before rewriting the original SQL. Table INSERT masking visits query expressions without constructing an execution sink, allowing ordinary JOB display when no connection context is attached.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (INSERT JOB display and masking)
PR Type: Bugfix

Problem Summary:

The session-independent table INSERT visitor omitted static partition value expressions. A syntactically valid scalar subquery containing S3 properties could retain its secret in display or audit text while the main query was masked. Visit every static partition value through the existing encryption visitor, preserving ordinary JOB display without requiring a session or target catalog.

### Details

- **Frequency:** INSERT statements with sensitive TVF properties in static partition expressions, including statements rejected later during analysis.
- **Root cause:** The table INSERT override visited the main query and leading CTE queries but skipped partitionSpec expressions previously visited by parseInsertPartitionSpec.
- **Why existing tests missed it:** Existing display and masking tests covered VALUES, SELECT, source/target TVFs and CTEs but no subquery inside a static partition value.
- **Fix:** Explicitly visit each partitionKeyValue expression and reuse the existing TVF property masking and SQL rewriting. Add tests with and without ConnectContext for one and multiple partition subqueries, constants and other partition forms.
- **Other paths and branches:** Main queries, both CTE placements and INSERT INTO TVF retain their existing visitors. Table names, branch names, labels, column lists, legacy hints and EXPLAIN options contain no other expression-bearing children outside those paths. BindSink still rejects non-literal static partition values.
- **Behavior change:** Static partition subqueries now receive the same masking as main-query subqueries. Execution SQL, session state, execution sink construction and persistence are unchanged.

### Testing

The unchanged production baseline reproduces the partition-secret assertion failure in both session modes using native run-fe-ut.sh and frozen tests. Source, executor, console, fresh XML and Checkstyle evidence are archived for each run.

The task gate runs the following native command and verifies the original 39 cases plus 6 new cases, zero failures/errors/skips, unchanged frozen tests, actual Checkstyle coverage of both changed Java files, and unchanged tracked files during execution:

```sh
bash run-fe-ut.sh --run org.apache.doris.job.extensions.insert.InsertJobDisplaySqlTest,org.apache.doris.nereids.parser.AuditEncryptionSessionVariableTest,org.apache.doris.nereids.parser.RepositoryAuditEncryptionTest,org.apache.doris.nereids.parser.EncryptSQLTest,org.apache.doris.nereids.trees.plans.commands.insert.InsertIntoTVFJobTest
```

Validation uses offline Maven 3.9.11 and ByteOpenJDK 17.0.9. No real BE/S3 execution, complete SQL regression suite or remote CI run was performed.

### Release note

S3 secrets in static INSERT partition subqueries are masked in SQL display and audit text, including SQL that is rejected during subsequent analysis. Ordinary INSERT JOB display continues to work without an attached connection context.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: real BE/S3 execution, complete SQL regression and remote CI were not run.

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: Production change, tests, verification evidence and this description.
- Human review: Pending; the Planner will arrange independent review of the cumulative change.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of all 17 changed files at 4bff357 found one new P2: the TVF callback replaces an executor-originated TIMEOUT with generic cancellation. The review converged after 2 rounds; all three reviewers returned NO_NEW_VALUABLE_FINDINGS in the latest round, and all candidates and initial risk items have explicit dispositions.

The four existing threads were independently rechecked. Executor binding (4480623182), worker context cleanup (4480622802), prepared-execution cancellation state (4609912404), and admission-token publication (4610944383) are addressed by this head. No already-reported P0/P1 issue still applies, so existing_blocking_comment_ids is empty. The new finding concerns cancellation reason propagation and does not duplicate those threads. No additional user focus was supplied.

Critical checkpoint conclusions:

  1. Goal: immediate, one-time S3 INSERT jobs enter the existing job/task framework; creation rejects recurring, delayed, streaming, LOCAL and HDFS forms. Inspected unit scenarios cover these restrictions.
  2. Scope and reuse: changes reuse existing planner, task, coordinator, filesystem and masking mechanisms; the Iceberg test adjustment preserves independent manifests for cancellation coverage.
  3. Concurrency and locks: worker/cancel threads share task monitors and per-execution state; live worker handles survive task-field release. Admission publication observes pending cancellation. No further reachable lock cycle was established; destination deletion/startup synchronization can wait for ongoing side effects.
  4. Lifecycle: executor scan work, connector groups, query callbacks, statement resources and worker thread-local cleanup are covered on success, failure and cancellation. Per-run state isolates repeated prepared executions. No C++ static initialization change.
  5. Configuration: no new settings; background tasks retain fresh default session values.
  6. Compatibility: table/streaming jobs and MTMV cleanup paths were traced; persisted keys and protocol formats are unchanged. No incompatible format change identified.
  7. Thrift/protobuf: neither directory changes, so field-ID comparisons are inapplicable.
  8. Parallel paths: direct/prepared TVF execution, scheduled table jobs, streaming rejection, source/target masking and both job display consumers were inspected.
  9. Conditional checks: explicit schedule/target restrictions and canceled/finished guards have concrete triggering scenarios; CTE and static-partition masking branches follow the grammar.
  10. Tests: inspected positive, negative, persistence, worker-reuse and latch-based concurrency tests. They omit executor-originated TIMEOUT through the TVF callback, as the inline finding explains. No real S3 end-to-end test is included.
  11. Test results: no generated result files change; assertions were checked against source behavior, without execution.
  12. Observability and errors: job/task identifiers and masked displays are retained, but timeout classification and client diagnostics regress in the reported P2. Other reviewed failure branches report ERR rather than success.
  13. Persistence/failover: task terminal fields and one-time job completion flow through existing job EditLog/replay; raw execution SQL remains persisted and the display cache rebuilds after restore. No new journal format.
  14. Writes/atomicity: creation validation does not delete or dispatch to the destination. External TVF output retains its existing non-transactional semantics, including possible partial files on failure/cancel/crash. Table transaction, visible-version and delete-bitmap behavior are not changed.
  15. FE-BE variables: no new transmitted field or alternate sending path requires propagation.
  16. Performance: no new per-row work or unbounded retry found; display masking caches its result and task cleanup remains bounded by the existing resource lifecycles.
  17. Further sweep: rechecked all changed paths, existing threads, candidate dispositions and risk items, including suspected multi-task lock inversion and late prepared callbacks. No additional substantiated finding or unresolved code question remains.

Validation is static inspection only. No builds, tests, benchmarks, service startup or external S3 execution were performed; runtime behavior is not proven by this review.

Review converged after 2 round(s).

### Background

INSERT INTO TVF registers an executor cancellation callback for each execution. It cancels the coordinator before waiting for dispatch to leave its execution lock, then cancels again to cover fragments started during that handoff.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (TVF insert execution)
PR Type: Bugfix

Problem Summary:

Executor timeouts run the TVF callback before forwarding their status to the coordinator. The callback replaced TIMEOUT with CANCELLED and a generic message, which became the first terminal status. Retain the executor's first reason in each execution and preserve its classification and diagnostic through both cancellation phases and error handling.

### Details

- **Change map:** 17 production lines added and 13 removed; a 343-line regression class; five existing assertion replacements. No generated files or documentation in the source change.
- **Frequency:** When executor cancellation reaches a TVF insert before planning, during workload admission, or while waiting for execution.
- **Root cause:** The callback synthesized CANCELLED before the executor forwarded TIMEOUT; CoordinatorContext retains the first non-OK status. checkCanceled and catch also discarded the input diagnostic.
- **Why existing tests missed it:** Existing TVF tests expected generic cancellation text, while admission timeout tests called Coordinator.cancel directly.
- **Fix:** Read the existing sticky pending reason in the per-execution callback, publish it with a volatile Status, and reuse it for both coordinator cancellations, checkCanceled, and catch. Preserve the original dispatch handshake and cleanup.
- **Other paths and branches:** Existing RowLevelDmlCommand and ConnectorRewriteDriver already consume the pending reason. No executor API, Coordinator, task lifecycle, protocol, persistence, or branch changes.
- **Behavior change:** TIMEOUT retains its classification and message; ordinary cancellation and other first reasons retain their input diagnostics. A later cancellation does not replace the first reason or an existing coordinator failure.

### Testing

Native offline run-fe-ut.sh --run on the unchanged production baseline: all 18 selected new regression cases failed only their exact classification/diagnostic assertions, with zero errors or skips. Checkstyle covered all four Java files with zero violations. The full new test class is frozen for candidate verification.

The candidate's required native gate runs InsertIntoTVFCancellationReasonTest, InsertIntoTVFAdmissionCancellationTest, InsertIntoTVFPreparedExecutionTest, InsertIntoTVFJobTest, InsertIntoTVFCommandTest, InsertTaskLifecycleTest, TaskProcessorTest, StmtExecutorTest, and CoordinatorTest (119 existing cases plus 21 new cases). The gate checks fresh XML, unchanged test identities, native exit status, zero failures/errors/skips, Checkstyle coverage, and unchanged source/evidence hashes before delivery. JDK 17.0.9, Maven 3.9.11, Asia/Shanghai, one test fork, Maven offline and build cache disabled.

Real BE/S3, full SQL regression, and remote CI were not run.

### Notes for Reviewers

The admission regressions use real StmtExecutor.cancel, callback registration, Coordinator.cancel, and terminal-state updates. Existing prepared pre-cancel diagnostics retain their outer executor wrapping; the assertion now searches for the exact input reason. The task-level insert task canceled contract is unchanged.

### Release note

TVF inserts retain the original executor timeout or cancellation diagnostic instead of reporting a generic cancellation.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: local native FE unit gate; real BE/S3, full SQL regression, and remote CI not run.

### AI Disclosure

- Tool: Codex (GPT-6 Astra)
- Generated: Production change, regression tests, and this description.
- Human review: Pending.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of all 18 changed files at d548aec found one new P2 issue: remote destination deletion holds the lock needed by synchronous cancellation and can stall the FE timeout checker. Please address the inline finding. No verified P0/P1 findings remain.

The two existing P1 threads (4480623182, 4480622802) are fixed: InsertTask binds its executor before planning, and TaskProcessor retains/finalizes/closes the worker context. The three existing P2 threads (4609912404, 4610944383, 4616587630) are also fixed by per-execution cancellation state, post-publication token cancellation, and forwarding the executor's first cancellation reason. No duplicate comments are added.

Critical checkpoint conclusions:

Checkpoint Conclusion
Goal and evidence Immediate one-time S3 jobs use validation and the existing task executor; positive/negative unit tests were inspected. Runtime success is not proven by this static review.
Scope and reuse Creation, task lifecycle, masking and coordinator changes reuse existing facilities; the Iceberg fixture change retains independent queued manifests.
Concurrency and locks Worker/control/timeout threads share task state and per-execution cancellation state. Task snapshots and terminal transitions are synchronized. No reachable lock cycle was verified; holding executionLock over remote deletion causes the inline P2 liveness defect.
Lifecycle Executor/scan/statement ownership and cleanup were traced through success, failure, early initialization and cancellation. Prepared executions have independent cancellation state.
Configuration No configuration added; background tasks retain existing default session timeouts.
Compatibility Existing persisted task fields and raw execution SQL are retained; masked display SQL remains transient. No new incompatible symbol or storage format identified.
Thrift/protobuf Neither is changed.
Parallel paths Table INSERT labels/runWithUpdateInfo, streaming/ALTER restrictions, shared MTMV finalization, and direct/prepared TVF paths were inspected.
Conditional checks Immediate/S3-only validation and terminal checks address concrete supported forms and races; no additional conditional defect verified.
Test coverage Creation restrictions, masking, CTE/partition forms, recovery, task teardown, admission, timeout reasons and prepared reuse have unit coverage. Cancellation during recursive destination deletion needs a test with the fix.
Expected results No golden result files changed; added unit assertions and fixture changes were inspected.
Observability Task errors/timestamps and job/task identifiers remain available; raw SQL was removed from the task failure log and display-masking failures are redacted. No new metrics requirement identified.
Persistence and failover Success/failure callbacks and explicit cancellation logging cover existing job/task fields; serialization/replay paths were inspected. External output is not a Doris transaction and does not acquire exactly-once replay guarantees.
Writes and atomicity Creation does not delete destination files or dispatch output. Execution retains existing nontransactional external-output semantics; partial files can remain on failure/cancel/crash.
FE/BE variables No new transmitted fields or propagation paths.
Performance No new hot-path allocation/scaling defect verified beyond lock-held remote I/O in the inline finding; display masking is cached.
Other risks and user focus No additional user focus was supplied. All initial risk items and candidates have evidence-backed dispositions; no unresolved static coverage gap remains.

Validation was static inspection only: no builds, tests, benchmarks, submodule initialization or source edits. Remote S3 end-to-end behavior was not executed. Review convergence was reached in round 2 after both complete reviewers and the separate cancellation-risk reviewer reported NO_NEW_VALUABLE_FINDINGS against the final candidate set.

Review converged after 2 round(s).

### Background

INSERT INTO a TVF can recursively delete existing destination files in the FE before starting fragments. The statement executor synchronously invokes the command's cancellation callback, including when cancellation is requested without waiting for command completion.

### What problem does this PR solve?

Issue Number: None
Related PR: None
PR Type: Bugfix

Problem Summary:

Slow destination deletion holds the TVF execution lock while cancellation waits for that lock. This can block the FE's single timeout checker and a caller using cancel(false). Move the complete deletion and FileSystem cleanup outside the startup lock while retaining cancellation checks before deletion and inside the fragment-startup handoff.

### Details

- **Change map:** Four added and four removed production lines move the deletion/check and clarify the lock's purpose; one new test class covers ten scenarios. No existing test assertions or generated files change.
- **Frequency:** Cancellation while delete_existing_files=true is performing slow remote filesystem work.
- **Root cause:** ExecutionState.cancel synchronously reacquires executionLock, which was also held across FileSystem creation, recursive delete and close.
- **Why existing tests missed it:** Existing tests covered planning, admission, dispatch and waiting but did not hold a real TVF command at an external filesystem boundary.
- **Fix:** Run deletion outside executionLock, keep the pre-deletion and locked pre-dispatch checks, and preserve the two-phase coordinator cancellation and exec startup critical section. The execution thread retains cleanup ownership; cancellation does not interrupt or roll back remote deletion already in progress.
- **Other paths and branches:** Direct INSERT, jobs and prepared statements share this command. No global cancellation API, other production path or release branch changes.
- **Behavior change:** Cancellation can return while destination I/O remains active; cancellation observed after that I/O prevents channel reset, fragment startup and success reporting. A subsequent deletion failure retains the original cancellation reason.

### Testing

The frozen native negative control runs the actual ConnectContext.checkTimeout/killByTimeout/StmtExecutor.cancel chain and actual cancel(reason,false) with recursive delete blocked by a latch. Both fail on unchanged production at explicit cancellation-blocked assertions, with zero errors or skips; cleanup releases the latch and drains both workers.

The kernel gate runs run-fe-ut.sh --run with InsertIntoTVFDeletionCancellationTest and the nine existing lifecycle classes, checking all 140 original test identities plus ten new cases, fresh native XML, zero failures/errors/skips, native exit status, and actual Checkstyle coverage for both changed Java files. Tests also cover filesystem creation/close blocking, cancellation followed by deletion failure, pre-cancellation, normal deletion/dispatch order and uncanceled deletion failure. Gate results and immutable execution evidence are recorded separately.

No real BE/S3, full SQL regression or remote CI run is claimed.

### Release note

Cancellation of INSERT INTO TVF no longer waits for remote destination deletion or its filesystem cleanup. Remote deletion already in progress can continue; cancellation during that I/O is checked before fragment startup.

### Check List (For Author)

- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Partially verified: real BE/S3, full SQL regression and remote CI have not been run.

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: Production change, new tests and this description.
- Human review: Not yet performed; agent self-review is recorded separately and independent review follows the gate.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of all 19 changed files at ebc93a4471c92f6709f45a3c8918d0808f0109a0: no new actionable findings. Two complete-scope reviewers and a separate cancellation-risk reviewer returned NO_NEW_VALUABLE_FINDINGS; the main agent independently checked their evidence and completed the final sweep.

All six earlier findings are addressed in this head: executor binding (4480623182), worker context cleanup (4480622802), prepared execution isolation (4609912404), admission-token publication (4610944383), original cancellation reason (4616587630), and deletion outside the cancellation lock (4617672123). Neither earlier P1 still applies, so no existing blocking comment is retained or duplicated.

Critical checkpoint conclusions:

  • Goal and correctness: the immediate, one-time S3 job form follows the existing job scheduler and TVF execution path. Creation validates the target, properties and query without destination deletion or dispatch. Negative and lifecycle unit tests cover these contracts.
  • Scope and reuse: production changes stay in existing creation, task, masking and coordinator paths. The Iceberg-only test change preserves independent manifests for its cancellation fixture.
  • Concurrency: task publication and terminal transitions use the task monitor; execution retains local handles. Queue publication honors pending cancellation. Remote deletion is outside the dispatch lock. Startup synchronization and bounded RPC waits follow the existing coordinator mechanism; no new lock inversion was established.
  • Lifecycle and memory ownership: worker executor finalization and statement closure cover initialization failure, success, failure and cancellation. Per-execution callbacks isolate prepared executions. No BE allocation or static initialization changes.
  • Configuration: no new configuration; background execution uses a fresh session's timeout settings.
  • Compatibility: existing persisted SQL/task fields are reused; no new storage format, connector SPI or wire-symbol change.
  • Thrift/protobuf: untouched.
  • Parallel paths: direct, prepared and scheduled TVF execution, table INSERT jobs, SELECT admission and generic TaskProcessor callers were traced; no additional required path change found.
  • Conditions and errors: S3-only/immediate-only restrictions fail explicitly. Join timeout, backend failure and cancellation cannot follow the inspected success path; sticky cancellation diagnostics are preserved.
  • Tests: added JUnit 5 negative, recovery and latch-controlled concurrency cases were inspected. No builds or tests were run during this static review; S3/MinIO end-to-end behavior remains unvalidated at runtime.
  • Expected results: no regression output files changed.
  • Observability: task/query identifiers, terminal task history and error diagnostics remain available; no material new metric gap found.
  • Persistence and failover: existing edit-log/replay structures and terminal callbacks are retained, with task-id cancellation persisted. No new exactly-once output guarantee is implied.
  • Writes and atomicity: validation does not write the destination. Execution retains existing non-transactional S3 semantics, including possible partial files after failure, cancellation or process loss; table transaction behavior is retained. Visible-version and delete-bitmap mechanisms are unchanged.
  • FE/BE variables: none added.
  • Performance: no material new hot-path scan or allocation issue established; display masking is cached. The extra journal write on explicit task cancellation is redundant but was not substantiated as a material defect.
  • Additional concerns and coverage: parser traversal, context-free recovery masking, late callbacks and cleanup exceptions were rechecked. No unresolved code candidate or uncovered changed file remains. The focus file supplied no additional user concern.

The review converged after one round. This conclusion is based on static source and test inspection, with the runtime limitations stated above.

Review converged after 1 round(s).

### Background

The existing PR and master both stabilize the Iceberg SDK cancellation
fixtures by preventing automatic manifest merging.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (existing PR), apache#70675 (upstream fixture update)
PR Type: Build/CI/Chore

Problem Summary:

The two equivalent fixture changes conflict when integrating master.
Merge master and retain its exact Iceberg test file, including the newer
test coverage and the assertions on queued readers and cancellation.

### Details

- **Affected:** FE test integration; both existing Git histories are retained.
- **Developer and release impact:** Restore mergeability without changing the PR's feature behavior.
- **License and third-party:** None.
- **Rollback:** Revert this merge with its first parent as the mainline.

### Testing

- Git merge-tree reproduced the single-file conflict before resolution.
- git diff --check passed for the resulting PR delta against master.
- Verified the resolved test blob equals master and retains its cancellation assertions.
- Verified every other resolved blob equals Git's automatic merge output.
- Local runtime tests were not run; CI must validate the new merge commit.

### Release note

None.

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Partially verified: runtime CI is pending on the new merge commit.

### AI Disclosure

- Tool: Codex (GPT-6)
- Generated: Merge resolution, structural checks and this commit description.
- Human review: Not stated.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Static review of all 18 changed files at 634054548cce5533e824234d53a1bba24659434a: no new actionable findings. Two complete-scope reviewers and a separate cancellation-risk reviewer returned NO_NEW_VALUABLE_FINDINGS. The main agent independently verified their evidence and completed the final sweep. The review converged in one round.

All six earlier findings are addressed at this head: executor binding (4480623182), worker context cleanup (4480622802), prepared-execution cancellation isolation (4609912404), admission-token publication (4610944383), original cancellation reason (4616587630), and deletion outside the cancellation lock (4617672123). Neither prior P1 remains applicable, so no existing blocking comment is retained. No duplicate inline finding is posted.

Inspected execution flow: CREATE JOB -> schedule/target/query validation -> persisted InsertJob -> scheduler/TaskProcessor -> InsertTask -> TVF planning and coordinator registration -> destination preparation/dispatch -> join/status -> terminal task history and EditLog -> executor/statement cleanup. Cancellation and timeout threads were traced through StmtExecutor callbacks, admission token publication and dispatch synchronization.

Critical checkpoint conclusions:

Checkpoint Conclusion from static inspection
Goal and supporting tests Immediate, one-time S3 INSERT jobs use the existing scheduler and TVF execution path. Creation rejects unsupported schedules and LOCAL/HDFS job targets; positive and negative unit cases cover these contracts.
Scope and reuse Seven production files change validation, execution, lifecycle and display masking; eleven test files cover these mechanisms. Existing planner, coordinator, filesystem and job facilities are reused.
Concurrency and locks The task monitor serializes initialization, handle snapshots and terminal transitions. Worker-local handles survive cancellation. Per-run state and the executor's first cancellation reason protect prepared reuse. Token publication handles cancellation on either side of publication. Filesystem creation/delete/close and join stay outside the dispatch lock; no new reachable lock inversion was substantiated.
Lifecycle and memory ownership Executor binding covers planning-time scans; worker finalization closes scan scope, query callbacks and StatementContext before removing the thread-local. Coordinator cleanup covers registration/dispatch/wait failures. Parallel MTMV closure remains idempotent. No BE allocation or static initialization change.
Configuration No new configuration. Background tasks retain fresh-session timeout settings.
Compatibility and rolling upgrades Existing job/task serialization and TVF sink formats are reused; no incompatible storage format, function symbol or wire change was identified. This is an FE execution capability change.
Thrift/protobuf IDs Neither directory changes; no field or enum ID comparison is applicable.
Parallel paths Table INSERT retains labels and runWithUpdateInfo; recurring/delayed table and streaming table jobs retain their paths. Direct/prepared TVF execution, SELECT admission, ALTER restrictions and generic TaskProcessor callers were traced.
Special conditions and errors Immediate/S3-only checks reject unsupported forms explicitly. Terminal guards prevent late callbacks overwriting cancellation. Timeout, backend and dispatch failure branches report errors; the executor's first cancellation reason is preserved.
Test coverage Inspected validation, masking, CTE/static-partition traversal, recovery, terminal persistence, worker reuse, planning/admission/dispatch/deletion/wait cancellation and prepared-execution cases. JUnit 5 tests use controlled latches/futures for races. Real S3 end-to-end execution remains unverified.
Expected results No regression output files change. Added and adjusted unit assertions were checked against the source paths; test success is not claimed.
Observability Job/task identifiers, terminal timestamps and error diagnostics remain available. Displays use derived masked SQL, masking failures return redaction, and the task failure log omits raw SQL. No material new metric gap was established.
Persistence and failover Existing task fields, serialized history and EditLog/replay paths are retained; explicit task cancellation records terminal state. The display cache is transient and recomputed after recovery. No new journal format or exactly-once output guarantee is introduced.
Writes, atomicity and crashes Creation validation does not delete destination files or dispatch output. External TVF writes retain existing nontransactional semantics, including possible partial output after failure/cancellation/process loss. Table transactions, visible versions and delete bitmaps are unchanged.
FE/BE variable propagation No new cross-process variable or alternate serialization field needs propagation.
Complexity and performance No material new per-row work, unbounded retry or allocation regression was established. Successful display masking is cached.
Other concerns and user focus The focus file supplies no additional concern. All initial risks and candidate points have evidence-backed dispositions; no unresolved source question or changed-file coverage gap remains.

Validation limits: static source and test inspection only. No builds, tests, benchmarks, service startup, runtime race reproduction, S3 execution or failover exercise was performed. No repository source was modified.

Review converged after 1 round(s).

@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

run cloud_p0

@freemandealer

Copy link
Copy Markdown
Member Author

run external

@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

### Background

An immediate S3 INSERT job uses the workload-group admission queue while it starts. A full group can leave the job waiting while another session cancels the task or stops the job.

### What problem does this PR solve?

Issue Number: None
Related PR: apache#70282 (adds immediate S3 INSERT jobs)
PR Type: Test

Problem Summary:

Exercise the admission race from both job entry points. A cancellation received between allocation and publication of the waiting token must let the task finish while the holder keeps the only slot.

### Details

- **Scenarios:** Cancel a running task by ID and stop its job on the same saturated queue. Verify timely return, the task and job states, a single cancellation, query and worker cleanup, release of the waiting token, and zero fragment dispatches.
- **What existing tests miss:** The existing admission test cancels the statement executor directly. The task lifecycle tests inject command outcomes and do not run the scheduled TVF insert through the admission queue.
- **Fails when broken:** Reverting the post-publication cancellation check in the coordinator makes both job operations block past the bounded assertion.
- **External dependencies:** The FE test uses a local test table and mocked backend. It does not connect to S3.

### Testing

18 tests passed locally across `InsertTaskLifecycleTest` and `InsertIntoTVFAdmissionCancellationTest`, including both job cancellation entries. Removing only the pending-status check in `Coordinator.enqueue` made each entry exceed the five-second cancellation deadline with the only queue slot still occupied. Restoring the check let both return before that slot was released.

### Release note

None

### Check List (For Author)

- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Ready

### AI Disclosure

- Tool: OpenAI Codex (GPT-6)
- Generated: Job regression tests, shared test fixture and description update.
- Human review: Not stated for this change.
@freemandealer

Copy link
Copy Markdown
Member Author

run buildall

@freemandealer

Copy link
Copy Markdown
Member Author

/review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants