Repository navigation
[Bug][file base] Csv header fixed ‘,’ - #10257
jiamin13579 wants to merge 11 commits into
Conversation
|
Please add a test class |
|
Very good pr, this bug is very hidden, thanks for pointing it out. |
+1, I noticed that the example of e2e uses ','. You can add another delimiter, such as ";" |
Thanks, added |
|
Hi @jiamin13579, thanks for catching this. I reviewed the PR locally on branch What This PR Solves
Simple example: with 1. Code Change Review1.1 Core Logic AnalysisThe real runtime path is: Before: fsDataOutputStream.write(String.join(",", seaTunnelRowType.getFieldNames()).getBytes());After: fsDataOutputStream.write(
String.join(fieldDelimiter, seaTunnelRowType.getFieldNames()).getBytes());Key findings:
1.2 Compatibility ImpactJudgment: fully compatible. No API, config name, default value, protocol, or serialization contract changes. Default comma-delimited CSV output remains the same. Non-comma header output is corrected to match the existing configuration contract. 1.3 Performance / Side EffectsNo meaningful performance impact. Header generation still happens only once per output file. 1.4 Error Handling And LogsNo new error handling is introduced. Existing IO exception wrapping remains unchanged. Issue 1: Current GitHub Build is failing and the detailed log has expired
Issue 2: The new E2E writes the file but does not verify the header delimiter
2. Code QualityThe Java code change is clean and minimal. The test coverage should be tightened so it fails if the delimiter regresses. 3. ArchitectureThis is a precise bug fix. CSV data rows already use 4. Issue Summary
5. Merge DecisionConclusion: can merge after fixesBlocking item:
Recommended item:
Overall, the code fix is correct and low-risk. Once CI is green and the regression test verifies the header content, this should be ready to merge. |
|
Thanks for the original contribution. I picked this up and rebased the branch onto the latest I also replaced the write-only E2E coverage with direct output assertions for the default comma, a multi-character delimiter, and UTF-16LE with non-ASCII header/data. The effective PR diff is now limited to GitHub CI has been triggered on the updated head. Thank you again for identifying this issue and contributing the initial fix. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the contribution! I re-reviewed the full current diff and the relevant CSV header delimiter/charset handling runtime path.
I do not see a source-side blocker on the current head. The remaining Build failure is outside this two-file CSV path, so CI remains outstanding.
Daniel's repository permission is read-only, so this COMMENTED review records the technical conclusion only; it does not change GitHub's approval summary. A write-capable maintainer may still need to complete the repository approval gate.
|
please run |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the update. I re-reviewed the complete current diff at d8c22185fbdff2039e5a170c4157c501236bb0e4.
The runtime fix is correct: CsvWriteStrategy now writes the header with the configured field delimiter and charset, matching the data-row path. The regression cases also directly assert the default comma, a multi-character delimiter, and UTF-16LE output.
I found one documentation-completeness blocker in the new test code:
CsvWriteStrategyTest.java:59adds the non-trivialwriteCsvWithHeader(...)helper without Javadoc, andCsvWriteStrategyTest.java:248adds theTestCsvWriteStrategytest subclass without the required class-level Javadoc. Please document the helper's in-memory filesystem/encoding contract and the test subclass's purpose and boundary.
I do not see another source-side blocker in the two-file diff. The current required Build is still failing, so CI also remains outstanding after this documentation fix.
DanielLeens
left a comment
There was a problem hiding this comment.
Basic information
- PR title: [Bug][file base] Csv header fixed ‘,’
- Author: jiamin13579
- Link: #10257
- Base branch: dev
- State: OPEN
- Change size: +93 / -3, 2 file(s)
- Human review ready: No
- Review time: 2026-07-26T11:28:58Z
- Local branch: seatunnel-review-10257
- Local worktree: dedicated PR 10257 review worktree
Stable review keys
- pr_number:
10257 - base_sha:
358ce6172c5efd8da41438a8a0236bfb00d6ecc5 - reviewed_base_sha:
358ce6172c5efd8da41438a8a0236bfb00d6ecc5 - merge_base_sha:
358ce6172c5efd8da41438a8a0236bfb00d6ecc5 - head_sha:
d8c22185fbdff2039e5a170c4157c501236bb0e4 - reviewed_head_sha:
d8c22185fbdff2039e5a170c4157c501236bb0e4 - technical_verdict:
blocking - github_review_event:
NOT_POSTED - human_review_ready:
false - intended_change_correctness:
blocking - diff_integrity:
blocking - deletion_total:
3 - deletion_classified:
3 - deletion_unclassified:
0 - other_total:
3 - other_confirmed:
1 - other_resolved_in_current_head:
2 - other_rejected_with_same_proposition_evidence:
0 - other_not_applicable_with_reason:
0 - other_unresolved:
0 - merge_conclusion:
fix_then_merge - reviewed_at:
2026-07-26T11:28:58Z
CI, compare, and merge-gate facts
- mergeStateStatus:
BLOCKED - reviewDecision:
REVIEW_REQUIRED - mergeable_state:
blocked - mergeable:
True - rebaseable:
False - required_ci_gate:
failing - approval_gate:
pending - conflict_gate:
satisfied - merge_queue_gate:
pending - compare: status=
diverged, ahead_by=6, behind_by=65, total_commits=6, url=dev...d8c2218 - Gate assessment: PR-owned Spotless failure and deterministic missing-import blocker remain independently; the unchanged StarRocks dead link is baseline failure. No dirty conflict; REVIEW_REQUIRED.
What problem this PR solves
- User pain: CSV rows honor field_delimiter and encoding, but generated headers were comma-separated and JVM-default encoded.
- Fix approach: CsvWriteStrategy.enableWriteHeader joins field names with the configured delimiter and encodes the header and row delimiter with the configured charset.
- One-line summary: The production change aligns headers with row CSV settings, but the test source cannot compile because a required import was deleted.
- Before: With field_delimiter="||" and UTF-16LE, the header was default-encoded id,name while the row was UTF-16LE 1||Alice.
- After: Header and row both use UTF-16LE and ||: id||name followed by 1||Alice.
1. Code-change review
1.1 Core logic and real call/execution chain
- Behavior before: Header used fixed String.join(",") and platform-default getBytes while rows used configured delimiter/charset.
- Behavior after: Header fields and row delimiter use fieldDelimiter and charset, matching row serialization.
- Normal-path hit:
conditional— Hit once per newly created CSV output file when enable_header_write=true.
Changed files, classes, and methods
seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategy.java:70-180CsvWriteStrategy.enableWriteHeader— Writes the CSV header with configured delimiter/charset.seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java:83-263writeCsvWithHeader/TestCsvWriteStrategy— Uses an in-memory Hadoop stream to verify delimiter/encoding/header transaction behavior.
Effective prerequisites
- CSV writer, header enabled, first output-stream creation.
Conditions where the change does not apply
- Not applicable when headers are disabled or for non-CSV writers.
Complete execution chain
1. seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategy.java:55-100 -> CsvWriteStrategy constructor/setCatalogTable [lifecycle]
Unifies header and row configuration sources.
Side effect: Reads fieldDelimiter/charset/header options and configures CsvSerializationSchema.
2. seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategy.java:100-170 -> getOrCreateOutputStream/write [method_call]
Writes one header per new stream.
Side effect: NONE, LZO, and fallback creation branches all call the same header method.
3. seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategy.java:170-190 -> enableWriteHeader [serialization]
Produces header bytes consistent with rows.
Side effect: Uses String.join(fieldDelimiter) and getBytes(charset).
- Recovery, exception, async, serialization, and concurrency paths: No checkpoint/commit/file-move change; each newly created file after recovery gets one header through the existing lifecycle. Charset parsing and IO errors reuse existing handling.
Multi-table Sink Writer contract audit
- Applicable:
false - Sink implements SupportMultiTableSink:
Not reported by GitHub - createWriter returns the required subclass:
Not reported by GitHub - optionRule contains the replica option:
Not reported by GitHub - Evidence: Not applicable: file CSV writer; no multi-table sink writer is added.
1.2 Compatibility impact
- Classification:
fully_compatible(fully compatible) - API: No API change.
- SPI: No SPI change.
- Configuration: Reuses field_delimiter, encoding, and enable_header_write.
- Defaults: Defaults remain; only incorrect header bytes change.
- Protocol and serialization: CSV header now conforms to the published delimiter/encoding contract.
- Checkpoint/restore: No state-format change.
- Historical behavior: Existing correct row behavior is unchanged.
- Migration guidance: No migration required.
- Incompatible-changes documentation: Fully compatible; no incompatible-change entry needed.
1.3 Performance and side effects
- CPU: One join/encoding per file; no new hot path.
- Memory: Only a short header byte array.
- GC: No meaningful change.
- Network: No change.
- Lock contention: No change.
- Concurrency safety: Header is written before stream publication under the existing concurrency boundary.
- Retry: No change.
- Idempotency: Still one header per created stream.
- Resource release: No new resource ownership.
- Overall: Production overhead is negligible.
1.4 Error handling and logging
- Exception propagation: EncodingUtils parses charset at construction and header IO follows getOrCreateOutputStream IOException handling.
- Context: No new swallowed exception.
- Log levels: No new logging.
- Sensitive information: No sensitive fields.
- Overall: Reuses existing error boundaries.
1.5 Diff integrity, deletion ledger, and scope audit
- intended_change_correctness:
blocking - diff_integrity:
blocking - deletion_ledger: total=
3, classified=3, unclassified=0 - Reconciliation: 3 = 3 + 0
Deletion, rename, and disappeared-capability ledger
deletion-001| count=1|deletion|intended_change|seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategy.java(old hardcoded comma header write line) — Replaced by configured-delimiter header output.deletion-002| count=1|deletion|intended_change|seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategy.java(old platform-default row-delimiter bytes line) — Replaced by configured-charset encoding.deletion-003| count=1|deletion|unrelated_accidental|seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java(old LocalFileSystemConf import) — Two uses remain, so deleting the import deterministically breaks test compilation.
Scope and base-drift items
-
No out-of-scope hunk, stale-base change, or merge artifact requires a separate ledger entry.
-
Out-of-scope hunk conclusion: No out-of-scope hunk beyond the accidental import deletion.
-
Stale-base conclusion: None found.
-
Merge-artifact conclusion: None found.
2. Code-quality assessment
2.1 Code conventions, title format, and comments
- Title format: Title English/module token is nonstandard, non-blocking.
- Code conventions: git diff --check is clean; Spotless rejects the test expression at line 121.
- Comment completeness: New helper/subclass lacks required Javadocs.
2.2 Test coverage and stability
- Unit tests:
covered— Adds default, ||, and UTF-16LE non-ASCII cases. - Component tests:
covered— Mock FSDataOutputStream exercises real beginTransaction→write→finishAndCloseFile. - Engine integration tests:
not_applicable— Local serializer fix. - E2E:
not_applicable— Unit coverage is sufficient for header bytes after compile blockers are fixed. - Regression tests:
missing— The test source cannot compile, so new regressions have no executable CI evidence. - Stability classification:
stable
Test-stability evidence
CsvWriteStrategyTest.java:83-122- Trigger: Pure in-memory byte array and explicit charset.
- Probability basis: No sleep, port, network, container, ordering, or shared state.
- Analysis: Deterministic by design; static conclusion, not locally run.
Missing scenarios
- Compressed-header case; low residual risk because all branches share the header method.
2.3 Documentation
- User-visible change:
false - docs/en: No new option; no doc change required.
- docs/zh: No new option; no doc change required.
- Examples: Unit tests demonstrate delimiter/encoding behavior.
- Configuration truth: Implementation now matches existing option contracts.
- URL truth: No URL change.
2.4 Local-validation boundary and GitHub CI evidence
- Local boundary: Static diff/source/call-chain and current-head CI only.
Local execution boundary
compilation:not_executed— Not executed.unit_tests:not_executed— Not executed.integration_tests:not_executed— Not executed.e2e:not_executed— Not executed.packaging:not_executed— Not executed.docker:not_executed— Not executed.service_start:not_executed— Not executed.real_job:not_executed— Not executed.
Actually executed review commands
git diff --stat 358ce6172c5efd8da41438a8a0236bfb00d6ecc5...d8c22185fbdff2039e5a170c4157c501236bb0e4- Result:
passed - Explanation: Confirmed 2 files/93 additions/3 deletions.
- Result:
git diff --unified=0 358ce6172c5efd8da41438a8a0236bfb00d6ecc5...d8c22185fbdff2039e5a170c4157c501236bb0e4- Result:
passed - Explanation: Complete hunk/call-chain/deletion audit.
- Result:
git diff --check 358ce6172c5efd8da41438a8a0236bfb00d6ecc5...d8c22185fbdff2039e5a170c4157c501236bb0e4- Result:
passed - Explanation: No whitespace error; this does not mean Spotless passed.
- Result:
Required checks
- required_checks_status:
AVAILABLE Build| workflow=On pull request update| job=Not reported by GitHub| state=FAILURE| bucket=fail| conclusion=FAILURE| https://github.com/apache/seatunnel/runs/88969534320
Complete status-check rollup
Notify test workflow| workflow=On pull request update| job=Not reported by GitHub| state=COMPLETED| bucket=pass| conclusion=SUCCESS| https://github.com/apache/seatunnel/actions/runs/29933539920/job/88969116822labeler| workflow=Pull Request Labeler| job=Not reported by GitHub| state=COMPLETED| bucket=pass| conclusion=SUCCESS| https://github.com/apache/seatunnel/actions/runs/29933542818/job/88969126487Build| workflow=On pull request update| job=Not reported by GitHub| state=COMPLETED| bucket=fail| conclusion=FAILURE| https://github.com/apache/seatunnel/runs/88969534320
3. Architecture assessment
3.1 Solution type: precise fix / workaround / long-term design
- Type:
precise_fix - Assessment: Reusing configured delimiter/charset at the header serialization boundary is the minimal precise fix.
3.2 Maintainability
Header and row use the same normalized configuration.
3.3 Extensibility
Multi-character delimiters/charsets are naturally supported.
3.4 Historical-version compatibility
No state/API compatibility change.
4. Disposition ledger for findings from other reviewers
- total=
3, confirmed=1, resolved_in_current_head=2 - rejected_with_same_proposition_evidence=
0, not_applicable_with_reason=0, unresolved=0 - Reconciliation: 3 = 1 + 2 + 0 + 0 + 0
issuecomment-3696289978 — zhangshenghang
- Original proposition: Add a test class.
- Location: PR test coverage
- Thread: #10257 (comment)
- Current-head evidence: Current head adds three real-writer unit cases.
- Disposition:
resolved_in_current_head - Daniel disposition: Resolved.
issuecomment-3698298686 — LiJie20190102
- Original proposition: Add a non-comma delimiter regression.
- Location: CsvWriteStrategyTest delimiter case
- Thread: #10257 (comment)
- Current-head evidence: The || case asserts both header and row.
- Disposition:
resolved_in_current_head - Daniel disposition: Resolved.
issuecomment-5048236354 — nzw921rx
- Original proposition: Run Spotless to fix test formatting.
- Location: CsvWriteStrategyTest.java:121
- Thread: #10257 (comment)
- Current-head evidence: Fork Run / Code style job 88969118706 fails on the new return expression.
- Disposition:
confirmed - Daniel disposition: Confirmed; Daniel +1 and preserved as a formal finding.
- Aggregated finding:
issuecomment-5048236354
5. Formal findings
daniel-issue-1 — A still-used import was deleted, making the test source uncompilable
- Source reviewer: DanielLeens
- Location:
seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java:34-205 - Thread: Not reported by GitHub
- Problem and real execution path: The diff removes the LocalFileSystemConf import while lines 141/204 still instantiate LocalFileSystemConf.LocalConf. Maven testCompile → resolve unqualified LocalFileSystemConf → cannot find symbol.
- Current-head evidence: Imports at 20-53 omit the type while uses at 141/204 remain.
- Trigger condition: After Spotless is fixed, connector-file-base reaches test compilation.
- Potential impact: Deterministic compile failure; all new/existing writer tests cannot run.
- Best actionable fix: Restore the util.LocalFileSystemConf import, format, and let current-head CI compile/run.
- Severity:
high - Merge gate:
blocking - Current-head disposition:
confirmed_in_current_head - Already raised by another reviewer:
false - Other finding ID:
Not reported by GitHub
daniel-issue-2 — Non-trivial test helpers lack contract documentation
- Source reviewer: DanielLeens
- Location:
seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java:83-263 - Thread: Not reported by GitHub
- Problem and real execution path: writeCsvWithHeader builds an in-memory Hadoop stream, transaction, decode/split flow; TestCsvWriteStrategy exposes protected fields, all without Javadocs. Test helper → inject FS/transaction → real writer bytes → decode/split assertions.
- Current-head evidence: New helper/class at 83-122 and 249-263 lack required documentation.
- Trigger condition: Future changes to mock FS/encoding/transaction boundary.
- Potential impact: The non-obvious contract is easy to misuse/weaken.
- Best actionable fix: Document helper parameters/encoding/splitting and test-subclass injection boundary.
- Severity:
medium - Merge gate:
blocking - Current-head disposition:
confirmed_in_current_head - Already raised by another reviewer:
false - Other finding ID:
Not reported by GitHub
issuecomment-5048236354 — Current-head Spotless formatting failure
- Source reviewer: nzw921rx
- Location:
seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java:121-121 - Thread: #10257 (comment)
- Problem and real execution path: The new one-line return does not satisfy the formatter. Required Build → Run / Code style job 88969118706 → Spotless → line 121.
- Current-head evidence: The current fork job reports the exact formatting failure.
- Trigger condition: Every required code-style job.
- Potential impact: Build aggregator stays red and later verification is blocked.
- Best actionable fix: Run scoped Spotless, preserve semantics, and push.
- Severity:
medium - Merge gate:
blocking - Current-head disposition:
confirmed_in_current_head - Already raised by another reviewer:
true - Other finding ID:
issuecomment-5048236354
6. Findings summary
| ID | Finding | Location | Severity | Merge gate |
|---|---|---|---|---|
| daniel-issue-1 | A still-used import was deleted, making the test source uncompilable | seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java:34-205 | high | blocking |
| daniel-issue-2 | Non-trivial test helpers lack contract documentation | seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java:83-263 | medium | blocking |
| issuecomment-5048236354 | Current-head Spotless formatting failure | seatunnel-connectors-v2/connector-file/connector-file-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/file/writer/CsvWriteStrategyTest.java:121-121 | medium | blocking |
7. Merge conclusion
Conclusion:can merge after fixes
Blocking items
blocker-1[source] (daniel-issue-1): The test source still uses LocalFileSystemConf after its import was accidentally deleted, so module tests cannot compile.blocker-2[tests] (daniel-issue-2): New non-trivial test helpers/subclass lack the required purpose and contract documentation.blocker-3[tests] (issuecomment-5048236354): A new test expression fails Spotless on the current head, deterministically failing required Build.
Non-blocking recommendations
- No additional non-blocking finding is recorded.
Overall assessment
Production algorithm is correct, but test compilation/format/documentation gates block the current head.
Better alternative implementation and trade-offs
- Alternative: No new abstraction; restore the import, format the test, and document helpers.
- Trade-offs: The local fix minimizes change and keeps row/header consistent.
8. GitHub publication and reply readback
- Publication event:
COMMENT - Publisher identity:
DanielLeens(repository permissionREAD) - Reviewed commit:
d8c22185fbdff2039e5a170c4157c501236bb0e4 - This complete report is the submitted GitHub Review body. Its immutable review ID, URL, state, and submission time are verified from the GitHub API immediately after creation and retained in the local bilingual evidence.
- Any precise line-thread replies are separate GitHub objects and are likewise verified individually.
…ly Spotless Closes the three blocking findings from the 2026-07-26 review, all in CsvWriteStrategyTest: - Restored the org.apache.seatunnel.connectors.seatunnel.file.util .LocalFileSystemConf import that an earlier cleanup deleted while two LocalFileSystemConf.LocalConf usages remain, which made the whole connector-file-base test source fail compilation. - Added Javadoc to writeCsvWithHeader and TestCsvWriteStrategy stating their contracts: the helper drives one real writer lifecycle against an in-memory Hadoop stream and decodes the output with the SAME configured charset (that symmetry is what catches a platform-default encoded header), and the subclass only injects the mocked proxy and transaction identifiers without overriding any production logic. - Ran scoped spotless:apply, which wraps the over-length return expression the Code style job rejected. The production change (header honoring field_delimiter and encoding) is untouched.
|
Closed out the three blocking findings from the 2026-07-26 review — all in
Also merged current This is a genuinely nice little fix (headers finally honor |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point: for the File Sink's CSV writer, data rows already honor the configured
field_delimiterandencoding, but the generated CSV header line was always joined with a hardcoded comma and encoded with the JVM platform-default charset. Anyone usingenable_header_write = truetogether with a non-commafield_delimiter(or a non-defaultencoding) got a header line that didn't match the delimiter/encoding of the data rows underneath it — a real, user-visible correctness bug (originally reported and reproduced by @jiamin13579, endorsed by @chl-wxp as "very hidden"). - Fix approach:
CsvWriteStrategy.enableWriteHeader()now joins the field names with the configuredfieldDelimiterand encodes both the header bytes and the row-delimiter bytes with the configuredcharset, exactly mirroring how the data-row path (write()/CsvSerializationSchema) already behaves. - One-sentence summary: the CSV header now uses the same delimiter and encoding as the CSV body, closing a long-standing inconsistency between header and row serialization.
1. Code Change Review
1.1 Core Logic Analysis
Before:
fsDataOutputStream.write(String.join(",", seaTunnelRowType.getFieldNames()).getBytes());
fsDataOutputStream.write(rowDelimiter.getBytes());After:
fsDataOutputStream.write(
String.join(fieldDelimiter, seaTunnelRowType.getFieldNames())
.getBytes(charset));
fsDataOutputStream.write(rowDelimiter.getBytes(charset));Runtime path (file seatunnel-connectors-v2/connector-file/connector-file-base/src/main/java/.../sink/writer/CsvWriteStrategy.java):
User configures a File Sink with file_format_type=csv, enable_header_write=true, field_delimiter=<X>, encoding=<Y>
-> CsvWriteStrategy(FileSinkConfig) [ctor, L62-75]
this.fieldDelimiter = fileSinkConfig.getFieldDelimiter()
this.charset = EncodingUtils.tryParseCharset(fileSinkConfig.getEncoding())
-> write(SeaTunnelRow) [L110-124]
-> getOrCreateFilePathBeingWritten(row)
-> getOrCreateOutputStream(filePath) [L151-183]
(first time a given output file is opened)
-> enableWriteHeader(fsDataOutputStream) [L185-192]
if enableHeaderWriter:
write(join(fieldDelimiter, fieldNames).getBytes(charset))
write(rowDelimiter.getBytes(charset))
-> isFirstWrite.get(filePath) == true -> skip leading rowDelimiter (header already terminated the line)
-> write(serializationSchema.serialize(row)) (CsvSerializationSchema already uses fieldDelimiter + charset, untouched by this diff)
Key findings:
- This is hit on the normal write path for every newly-created CSV output file whenever
enable_header_write=true— not a recovery/edge-case-only branch. All threegetOrCreateOutputStreambranches (LZO, NONE, default/unsupported-compression-warn) callenableWriteHeaderthe same way, so the fix applies uniformly regardless of compression. - Header and data-row encoding/delimiter are now driven by the exact same
fieldDelimiter/charsetfields the constructor already populates for the row-serialization schema — no new state, no new config surface. isFirstWritebookkeeping (pre-existing, unchanged) still correctly avoids double-writing a row delimiter before the first data row, since the header write already appended one.- No change to checkpoint/commit, file-move, partition-path, or
CsvSerializationSchemarow-encoding logic — this is a tightly-scoped, single-purpose fix. - I checked the CSV-specific default:
BaseFileSinkConfigspecial-cases CSV so an unsetfield_delimiterbecomes","(not the generic�default used by other formats) — sotestHeaderUsesDefaultFieldDelimiter's"id,name"expectation is correct against the real config-resolution code, not just a lucky guess.
1.2 Compatibility Impact
Fully compatible.
- No API, SPI, config-option name, or default-value change.
field_delimiter,encoding, andenable_header_writeare pre-existing, already-documented options; the code now actually honors them for the header the way it always claimed to for the body. - Default CSV output (comma delimiter, no explicit encoding) is byte-for-byte unchanged in the common case where the platform default charset is already UTF-8 (true for essentially all Linux CI/production JVMs), so the vast majority of existing jobs see no output change at all.
- Jobs that previously set a non-comma
field_delimiterand/or a non-defaultencodingtogether withenable_header_write=truewill see their header bytes change — but the "old" header bytes were wrong (inconsistent with the row bytes below them), so this is a bug-fix correction of previously-broken output, not a removal of documented behavior. No incompatible-changes doc entry is warranted perdocs/en/introduction/concepts/incompatible-changes.mdconvention, matching the conclusion of all three prior review rounds. - No checkpoint/state-format change;
snapshotState/beginTransactionare untouched.
1.3 Performance / Side-Effect Analysis
No measurable impact. The header is still written exactly once per newly-opened output stream (String.join + one getBytes(charset) call); charset-aware encoding of a handful of field names is negligible compared to per-row serialization cost. No new allocations in the write hot path, no new locking, no new I/O calls.
1.4 Error Handling and Logging
No new exception paths. EncodingUtils.tryParseCharset (charset resolution) already ran at construction time before this PR; enableWriteHeader's IOException still propagates to the existing getOrCreateOutputStream catch block, which wraps it via CommonError.fileOperationFailed(...) exactly as before. No new logging, nothing sensitive.
Issue 1: Required Build check is still red on the current head, but for a reason unrelated to this PR's two files
- Location: GitHub Check
Buildon head4501a1606af2bb73887e4a1ae849ffa2eff08cd4, fork runjiamin13579/seatunnelrun32699429202(e.g. jobunit-test (8, ubuntu-latest),connector-file-local-it,connector-file-sftp-it, allupdated-modules-integration-test-part-*). - Problem: every one of these ~20 failing jobs fails at the exact same Maven reactor step, before the reactor even reaches
connector-file-base's own tests:I confirmed this is pre-existing on[ERROR] .../seatunnel-engine/seatunnel-engine-server/src/test/java/.../event/JobStateEventTest.java:[165,23] [ERROR] symbol: variable FAILED_JOB_EVENT_TIMEOUT_SECONDS [ERROR] location: class JobStateEventTestdevitself, not introduced by this PR:git grep FAILED_JOB_EVENT_TIMEOUT_SECONDS devfinds only the one usage atJobStateEventTest.java:165and no declaration or static import anywhere indev— the file statically importsRESTORE_TO_FAILED_TIMEOUT_SECONDSfromCheckpointErrorRestoreEndTestbut references a differently-named constant that doesn't exist.merge-base(dev, pr-10257) == dev HEAD (406c66789), so this PR is fully rebased and simply inherits dev's own compile break. Once the reactor fails to test-compileseatunnel-engine-server, every downstream module/job in the same Maven invocation (including the unrelated file-connector IT jobs) fails too — that's why the failure list looks broad even though only two CSV files changed.- By contrast,
Run / Code style,Run / License header,Run / Dead links, andRun / Sanity check resultsall pass on this head, confirming the three issues from the 2026-07-26 review round (missing import, missing Javadoc, Spotless formatting) are genuinely resolved.
- By contrast,
- Risk: the PR cannot get a green required
Builduntil this unrelateddev-red compile break is fixed upstream and this branch is rebased/re-run afterward. It is not something fixable inside this PR's own diff. - Best actionable fix: no code change needed in this PR; track/fix
JobStateEventTest.java'sFAILED_JOB_EVENT_TIMEOUT_SECONDSreference ondevseparately, then rebase this branch and re-trigger Build. - Severity: Medium (blocks the merge gate, but is external to this PR's own correctness).
2. Code Quality Assessment
2.1 Coding Standards
- Two-file diff, minimal and focused; no wildcard imports; new imports (
HadoopFileSystemProxy,FSDataOutputStream,Mockito,ByteArrayOutputStream,Charset,Arrays) are all used. - Comment completeness: the two non-trivial additions flagged in the 2026-07-24/07-26 rounds now both carry proper Javadoc:
writeCsvWithHeader(...)(CsvWriteStrategyTest.java:77-91) documents its in-memory-stream mechanism, the "same charset for config and decode" symmetry that is the whole point of the regression test, and each parameter/return value.TestCsvWriteStrategy(CsvWriteStrategyTest.java:142-147) documents that it only injects the mocked proxy/transaction identifiers and overrides no production logic.
- Title format (
[Bug][file base] Csv header fixed ‘,’) still uses smart quotes and a non-standard module token — cosmetic, already flagged as non-blocking in the 2026-07-26 round, unchanged and still non-blocking.
2.2 Test Coverage and Test Stability
- Three new unit tests directly exercise the fixed code path through the real production lifecycle (
beginTransaction→write→finishAndCloseFile→close), not a re-implementation of the logic:testHeaderUsesDefaultFieldDelimiter— default (comma) delimiter, UTF-8.testHeaderUsesMultiCharacterFieldDelimiter—"||"multi-character delimiter.testHeaderUsesConfiguredEncoding—"|"delimiter +UTF-16LEwith non-ASCII header/data (名称/测试), which is exactly the combination that would previously have produced garbled/incorrect header bytes.
- Mechanism:
HadoopFileSystemProxyis mocked so every requested output path returns the sameByteArrayOutputStream-backedFSDataOutputStream; the test then decodes the captured bytes with the same configured charset. This is a stronger regression guard than the E2E-write-only approach criticized in the very first (2026-04-20) review round — it fails deterministically if the header regresses to the hardcoded comma/platform-default-charset behavior, and it sidesteps the real-filesystem/Windows charset flakiness that motivated the earlier "Stabilize CSV header regression test on Windows" commit (these new tests are correctly not annotated@DisabledOnOs(OS.WINDOWS), unlike the older real-filesystem tests in the same file). - I traced field/method access:
hadoopFileSystemProxy,jobId,uuidPrefix,subTaskIndexare all declaredprotectedonAbstractWriteStrategy(.../file/writer/AbstractWriteStrategy.java:85-100), soTestCsvWriteStrategy'sthis.hadoopFileSystemProxy = proxyetc. is legal even though the test package (...file.writer) differs fromCsvWriteStrategy's package (...file.sink.writer) — protected access viathisinside a subclass is permitted regardless of package.HadoopFileSystemProxy.getOutputStream(String)(.../hadoop/HadoopFileSystemProxy.java:300) matches the mocked signature. - The previously-flagged accidental
LocalFileSystemConfimport deletion is confirmed restored and in use (CsvWriteStrategyTest.java:34, used at lines 158/221 in the pre-existingtestParquetWriteInt96/testCsv2tests) —git diff --checkis clean and the diff shows exactly the 2 intentional production-line deletions plus 0 accidental ones. - Stability classification: Stable. No sleeps, no ports, no containers, no shared mutable state, no ordering dependency — pure in-memory, single-threaded, deterministic byte comparison.
2.3 Documentation Updates
No config name, default, or public contract changed, so no docs/en/docs/zh update is required — consistent with all three prior review rounds' conclusion.
3. Architectural Soundness
3.1 Elegance of the Solution: Precise fix
Reusing the already-existing fieldDelimiter/charset fields (which the row-serialization path already consumed) at the header-write call site is the minimal, correct fix. No new abstraction, no new config, no new class hierarchy — it just makes the header consistent with the row.
3.2 Maintainability
Header and row now derive from a single source of truth for delimiter/encoding, removing a latent trap where a future contributor might otherwise "fix" the row path and forget the header path (or vice versa).
3.3 Extensibility
Multi-character delimiters and arbitrary charsets are handled naturally since the fix reuses String.join and getBytes(Charset) rather than any comma-specific logic.
3.4 Historical-Version Compatibility
No serialization/state-format/API change; nothing to migrate. Existing jobs that never touched field_delimiter/encoding for CSV headers are unaffected in practice (default charset is UTF-8 almost everywhere).
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Required Build check remains red, but the cause is a pre-existing dev-red compile break in seatunnel-engine-server (JobStateEventTest.java:165, undeclared FAILED_JOB_EVENT_TIMEOUT_SECONDS), unrelated to this PR's two-file CSV diff |
GitHub Check Build, fork run 32699429202 |
Medium |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed (sorted by severity)
- Issue 1 (Medium): the required
Buildcheck needs to go green before merge per repo convention, but the fix is not a change to this PR's files — it requires the unrelatedJobStateEventTest.javacompile break to be fixed ondevfirst, then this branch rebased and Build re-run. I want to be explicit that this is a CI/infra wait, not a code-quality gap in the CSV fix itself.
- Issue 1 (Medium): the required
-
Recommended fixes — non-blocking
- PR title still uses smart quotes/non-standard module token; cosmetic only, carried over from the 2026-07-26 round, not worth blocking on.
Overall assessment: this is a full, fresh re-review of the entire current diff (git diff dev...pr-10257, head 4501a1606af2bb73887e4a1ae849ffa2eff08cd4), not just the incremental commit. I re-verified every finding from the three prior rounds (2026-07-19, 2026-07-24, 2026-07-26) against the current head: the production fix is unchanged and correct, the accidental LocalFileSystemConf import deletion is restored, the missing Javadoc on writeCsvWithHeader/TestCsvWriteStrategy is now present, and the Spotless formatting issue is resolved (Run / Code style passes on this head). I did not find anything the prior rounds should have caught but missed — this round's only new information is that the required Build check is still red on the new head, and I traced that failure to its root cause to confirm it is pre-existing dev breakage rather than something this PR introduced. The production algorithm, its compatibility story, and its test coverage are all in good shape; the only remaining gate is external CI health.
|
The CI failure on the last push ( #11954 fixed it upstream at 2026-08-24 11:50 UTC. Re-merged current |
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem Does This PR Solve?
- User pain point: for the File Sink's CSV writer, data rows already honor the configured
field_delimiterandencoding, but the generated CSV header line was always joined with a hardcoded comma and encoded with the JVM platform-default charset. Anyone usingenable_header_write = truetogether with a non-commafield_delimiter(or a non-defaultencoding) got a header line that didn't match the delimiter/encoding of the data rows underneath it — a real, user-visible correctness bug (originally reported by @jiamin13579, endorsed by @chl-wxp as "very hidden"). - Fix approach:
CsvWriteStrategy.enableWriteHeader()joins field names with the configuredfieldDelimiterand encodes both the header bytes and the row-delimiter bytes with the configuredcharset, mirroring how the data-row path (write()/CsvSerializationSchema) already behaves. - One-sentence summary: the CSV header now uses the same delimiter and encoding as the CSV body, closing a long-standing inconsistency between header and row serialization.
1. Code Change Review
1.1 Core Logic Analysis
I diffed the current head (ad380c8681d9) against the head I fully reviewed on 2026-08-24 (4501a1606af2) restricted to the two production/test files, and it is byte-for-byte empty — CsvWriteStrategy.java and CsvWriteStrategyTest.java are unchanged. The only new commit is a merge of apache/dev into this branch. So the core-logic analysis from my last full review still stands and I re-verified it against the current head rather than re-deriving it from scratch:
Before:
fsDataOutputStream.write(String.join(",", seaTunnelRowType.getFieldNames()).getBytes());
fsDataOutputStream.write(rowDelimiter.getBytes());After:
fsDataOutputStream.write(
String.join(fieldDelimiter, seaTunnelRowType.getFieldNames())
.getBytes(charset));
fsDataOutputStream.write(rowDelimiter.getBytes(charset));Runtime path (.../connector-file-base/.../sink/writer/CsvWriteStrategy.java):
User configures File Sink: file_format_type=csv, enable_header_write=true, field_delimiter=<X>, encoding=<Y>
-> CsvWriteStrategy(FileSinkConfig) [ctor] this.fieldDelimiter / this.charset populated
-> write(SeaTunnelRow)
-> getOrCreateOutputStream(filePath) (first time a given output file is opened)
-> enableWriteHeader(fsDataOutputStream)
if enableHeaderWriter:
write(join(fieldDelimiter, fieldNames).getBytes(charset))
write(rowDelimiter.getBytes(charset))
-> write(serializationSchema.serialize(row)) (CsvSerializationSchema already uses fieldDelimiter+charset, untouched by this diff)
Key findings (re-confirmed against current head):
- Hit on the normal write path for every newly-created CSV output file whenever
enable_header_write=true— not a recovery/edge-case-only branch; allgetOrCreateOutputStreambranches (LZO, NONE, default) callenableWriteHeaderthe same way. - Header and data-row encoding/delimiter now come from the exact same
fieldDelimiter/charsetfields the constructor already populates for row serialization — no new state, no new config surface. isFirstWritebookkeeping (pre-existing, unchanged) still correctly avoids double-writing a row delimiter before the first data row.- No change to checkpoint/commit, file-move, partition-path, or
CsvSerializationSchemarow-encoding logic.
1.2 Compatibility Impact
Fully compatible. No API/SPI/config-option/default-value change. Default CSV output (comma delimiter, default charset) is unchanged in the common case (UTF-8 is the platform default on essentially all Linux CI/production JVMs). Jobs that previously combined a non-comma field_delimiter/non-default encoding with enable_header_write=true will see corrected header bytes — but the old bytes were already wrong (inconsistent with the row bytes below them), so this is a bug-fix correction of broken output, not a removal of documented behavior. No incompatible-changes.md entry warranted, consistent with all four prior review rounds' conclusion.
1.3 Performance / Side-Effect Analysis
No measurable impact — header write happens once per newly-opened output stream; nothing changes in the per-row hot path.
1.4 Error Handling and Logging
No new exception paths; IOException from enableWriteHeader still propagates to the existing getOrCreateOutputStream catch block, wrapped via CommonError.fileOperationFailed(...) exactly as before.
Issue 1 (CI diagnosis, not a code defect): required Build check is still red on the current head, but for a reason unrelated to the CSV files and unrelated to the compile break my last review flagged
- On my 2026-08-24T10:30Z review at head
4501a1606af2, the sole failure was a pre-existingdev-red compile break inseatunnel-engine-server(JobStateEventTest.java, undeclaredFAILED_JOB_EVENT_TIMEOUT_SECONDS). @davidzollo's comment at 2026-08-24T15:44Z correctly diagnoses that same root cause and confirms it was fixed upstream by #11954, then re-mergesdevinto this branch. I re-verified: the current head's two review files are unchanged, andgit diff dev...HEADcompare status isahead_by=9, behind_by=1— essentially caught up. - On the current head (
ad380c8681d9, fork run32746620203), I re-ran the check-run inventory: of 67 jobs in the fork'sRunworkflow, only one is failing —Run / unit-test (8, windows-latest). Its log shows a Maven reactor failure that has nothing to do withJobStateEventTestor CSV/File connectors:This is a transient Maven Central 502 while resolving an unrelated connector's ([ERROR] Failed to execute goal on project connector-maxcompute: Could not resolve dependencies ... Failed to collect dependencies at com.aliyun.odps:odps-sdk-core:jar:0.51.2-public -> com.aliyun:credentials-java:jar:0.3.12 -> com.sun.xml.bind:jaxb-core:jar:2.3.0: Failed to read artifact descriptor ... status: 502 Bad Gatewayconnector-maxcompute) transitive dependency, on the Windows/JDK8 lane specifically. It is an external artifact-repository availability blip, not something either this PR ordevcontrols, and it does not touch anything in the CSV write path. - Risk: the required
Buildgate is still red, purely from this one transient network failure on one OS/JDK lane. - Best actionable fix: no code change needed in this PR; rerun the failed
unit-test (8, windows-latest)job (job-level rerun, not a full workflow rerun) once Maven Central is healthy again. - Severity: Medium (blocks the merge gate, but is fully external/environmental).
2. Code Quality Assessment
2.1 Coding Standards
Two-file diff, minimal and focused; no wildcard imports. All three findings from the 2026-07-24/07-26 rounds (accidental LocalFileSystemConf import deletion, missing Javadoc on writeCsvWithHeader/TestCsvWriteStrategy, Spotless formatting) remain fixed on the current head — I re-verified the file contents directly rather than relying on the earlier review's word. Run / Code style, Run / License header, Run / Dead links, and Run / Sanity check results all pass on the current head. Title still uses smart quotes/a non-standard module token — cosmetic, previously flagged as non-blocking, unchanged.
2.2 Test Coverage and Test Stability
Three unit tests exercise the fixed path through the real production lifecycle (beginTransaction → write → finishAndCloseFile → close) against a mocked HadoopFileSystemProxy backed by an in-memory ByteArrayOutputStream:
testHeaderUsesDefaultFieldDelimiter— default comma delimiter, UTF-8.testHeaderUsesMultiCharacterFieldDelimiter—"||"multi-character delimiter.testHeaderUsesConfiguredEncoding—"|"delimiter +UTF-16LEwith non-ASCII header/data.
Stability classification: Stable. No sleeps, no ports/containers, no shared mutable state, no ordering dependency — pure in-memory, single-threaded, deterministic byte comparison. This is unchanged from my last review and I found nothing on this pass to revise.
2.3 Documentation Updates
No config name/default/public contract changed, so no docs/en/docs/zh update required — consistent with all four prior review rounds.
3. Architectural Soundness
3.1 Elegance of the Solution: Precise fix
Reuses the already-existing fieldDelimiter/charset fields at the header-write call site — the minimal, correct fix, with no new abstraction or config surface.
3.2 Maintainability
Header and row now derive from a single source of truth for delimiter/encoding, removing a latent trap for future contributors.
3.3 Extensibility
Multi-character delimiters and arbitrary charsets are handled naturally via String.join/getBytes(Charset).
3.4 Historical-Version Compatibility
No serialization/state-format/API change; nothing to migrate.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Required Build check is red on the current head due to a transient Maven Central 502 resolving an unrelated connector's (connector-maxcompute) dependency on the Windows/JDK8 lane only — unrelated to this PR's CSV diff and unrelated to the previously-flagged JobStateEventTest break (already fixed upstream and merged in) |
Run / unit-test (8, windows-latest), fork run 32746620203 |
Medium |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
-
Blockers — must be fixed (sorted by severity)
- Issue 1 (Medium): rerun the failed
unit-test (8, windows-latest)job so the requiredBuildcheck goes green. This is a CI/infra wait (transient Maven Central 502), not a code-quality gap — no further change to this PR's two files is needed.
- Issue 1 (Medium): rerun the failed
-
Recommended fixes — non-blocking
- PR title still uses smart quotes/non-standard module token; cosmetic only, carried over from earlier rounds, not worth blocking on.
Overall assessment: this is a fresh re-review of the current head. I confirmed the two reviewed files are byte-identical to the head I fully reviewed on 2026-08-24 (only a dev merge commit was added), so the production fix, its compatibility story, and its test coverage are unchanged and remain sound. @davidzollo's 2026-08-24T15:44Z comment correctly diagnosed and fixed the previously-flagged JobStateEventTest compile break by merging in #11954 from dev — I verified that fix landed cleanly. What's new on this pass is that the required Build check is still red, but now for a completely different and unambiguously environmental reason (a Maven Central 502 on one Windows/JDK8 job, resolving an unrelated connector's dependency) rather than a real compile break. Once that job is rerun successfully, I see nothing left blocking merge.
|
The CSV header repair is now at Headers honor the configured delimiter and charset. EN/ZH LocalFile documentation now explains that behavior, including the old workaround, and the existing real LocalFile IT adds a FakeSource-to-file job with The historical Maven Central 502 and the later cancelled file IT are distinct observations. The cancellation actor/cause was not established, so no job retry or human-cancellation override was performed. This follow-up makes the requested documentation/integration correction; it is not an empty CI trigger. The single post-push snapshot at 2026-10-26T10:32:35Z found the exact head mergeable, with review required and no Apache checks/source-fork runs yet. Current-head CI and effective approval remain required; no runtime or production acceptance is claimed. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the fix, @jiamin13579, and thanks to everyone who carried it through. I went through the full diff of the current head (383f9388) and traced the CSV sink path. The PR's own two-file diff is unchanged from the version I last reviewed (ad380c86); the head was updated only by a merge of dev, and I re-verified the production code and call chain against the new head. This review is by code reading only; nothing was executed locally.
What Problem Does This PR Solve?
- User pain point: with
enable_header_write = true, the CSV sink wrote the header joined by a hardcoded comma and encoded with the platform default charset, while data rows honorfield_delimiterandencoding. The header then did not match the rows below it. - Fix approach:
CsvWriteStrategy.enableWriteHeader()joins the field names with the configuredfieldDelimiterand encodes both the header and the row delimiter with the configuredcharset. - One-sentence summary: the CSV header now uses the same delimiter and encoding as the CSV body.
1. Code Change Review
1.1 Core Logic Analysis
Before / after (CsvWriteStrategy.java, enableWriteHeader):
// before
fsDataOutputStream.write(String.join(",", seaTunnelRowType.getFieldNames()).getBytes());
fsDataOutputStream.write(rowDelimiter.getBytes());
// after
fsDataOutputStream.write(String.join(fieldDelimiter, seaTunnelRowType.getFieldNames()).getBytes(charset));
fsDataOutputStream.write(rowDelimiter.getBytes(charset));Runtime path:
CsvWriteStrategy ctor: fieldDelimiter, charset, rowDelimiter, enableHeaderWriter from FileSinkConfig
write(row) -> getOrCreateOutputStream(filePath) // only when the file is first opened
-> LZO / NONE / default compress branches -> enableWriteHeader(stream) // changed method
write(row) -> serializationSchema.serialize(row) // already uses fieldDelimiter + charset
- All three compress branches call
enableWriteHeader, so the fix covers every output path, and the header is written once per file. fieldDelimiterandcharsetare final fields set in the constructor from the same config the serialization schema uses, so header and rows cannot diverge.
1.2 Compatibility Impact
Partially incompatible (intended bug-fix behavior change). For jobs with enable_header_write = true and a non-comma field_delimiter or a non-default encoding, the header line changes from comma-joined / platform-default bytes to the configured delimiter and charset. The old header was inconsistent with the body, but anyone who worked around that (for example by parsing the header with a comma) will see a change. With the default configuration (comma and UTF-8) the output bytes are identical on UTF-8 platforms. No option, default, or checkpoint format changes.
1.3 Performance / Side-Effect Analysis
None: one header write per output file.
1.4 Error Handling and Logging
Unchanged; IOException is handled by the existing getOrCreateOutputStream wrapper. No new issues.
2. Code Quality Assessment
2.1 Coding Standards
Minimal and focused: two production lines and one test class. The new test helpers carry Javadoc explaining their intent.
2.2 Test Coverage and Test Stability
Rating: Stable.
CsvWriteStrategyTest#testHeaderUsesDefaultFieldDelimiter(default,),#testHeaderUsesMultiCharacterFieldDelimiter(||) and#testHeaderUsesConfiguredEncoding(UTF-16LE with a non-ASCII header and data) drive the real writer lifecycle against an in-memoryByteArrayOutputStreamand decode the bytes with the configured charset. The delimiter tests fail if the hardcoded comma returns; the UTF-16LE test fails if the platform-defaultgetBytes()returns.- They are deterministic: no network, no sleeps, no fixed ports, and the mocked filesystem proxy hands back an in-memory stream, so nothing is written to disk despite the
/tmppath strings. - The earlier compile problem (missing
LocalFileSystemConfimport) and the Spotless wrapping are resolved in this version.
2.3 Documentation Updates
No doc change. field_delimiter and enable_header_write already describe the intended behavior and the code now matches. A one-line note in the file sink docs (EN and ZH) that the header follows field_delimiter and encoding would be nice, but is not required.
3. Architectural Soundness
3.1 Elegance
Precise fix.
3.2 Maintainability
Header and rows now derive from the same fields.
3.3 Extensibility
None needed.
3.4 Historical-Version Compatibility
See 1.2. Only the header line of files written with a non-default delimiter or encoding changes. No state or checkpoint impact.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Header behavior change for non-default delimiter / encoding jobs is not mentioned in the docs | file sink docs (EN and ZH) | Low |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
Blockers (must fix)
- None at the source level. The only gate is CI: this head has no check runs on the apache side and no workflow run on the fork for this SHA, so please make sure GitHub Actions is enabled on the fork and a full CI run completes and is green.
Recommended fixes (non-blocking)
- Issue 1: add a short note about the header following
field_delimiterandencoding(EN and ZH).
Overall assessment: a small, correct fix with meaningful regression tests; no non-CI blockers remain. Once CI is green on this head I would be comfortable approving. The branch is 2 commits behind dev with no conflicts, so a sync is not needed unless CI shows an unrelated failure.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for preserving the focused CSV fix while refreshing the base. I re-reviewed the entire two-file diff at 383f93887a195608f4bd05f4a9800080b79e4db9 and traced the writer/config/transaction path. The header correction and exact-byte-derived unit assertions are sound. Sorry for not carrying the earlier integration-test request and paired documentation requirement through my previous conclusion; those are carryovers, not new defects introduced by this base sync.
What Problem Does This PR Solve?
- User pain point: a CSV file can have a comma/platform-encoded header above rows using a configured delimiter/charset.
- Fix approach: write the header and its line delimiter with the same configured field delimiter and charset used by data rows.
- One-sentence summary: make a CSV header agree with its own file's rows.
Example: delimiter || must produce id||name above 1||a; UTF-16LE non-ASCII names must decode in the same charset as the rows.
1. Code Change Review
1.1 Core Logic Analysis
Full +115/-2 diff: CsvWriteStrategy.java:184-191 and existing CsvWriteStrategyTest.java:60-144,265-288.
Before:
stream.write(String.join(",", seaTunnelRowType.getFieldNames()).getBytes());
stream.write(rowDelimiter.getBytes());After:
stream.write(String.join(fieldDelimiter, seaTunnelRowType.getFieldNames()).getBytes(charset));
stream.write(rowDelimiter.getBytes(charset));Key findings:
- Ordinary CSV/TEXT stream creation reaches this only when enable_header_write=true; its default false remains unchanged.
- The constructor already resolves fieldDelimiter and charset from FileSinkConfig, and row serialization already receives those same values. This corrects the inconsistent header, without altering row serialization.
- Header creation still occurs once per opened file in each existing compression branch; file rolling, transaction paths and checkpoint commit behavior are unchanged.
- The test subclass injects a mock filesystem/transaction context but overrides no writer logic, so the asserted bytes come from the real header/row lifecycle.
Complete affected chain:
FileSinkConfig -> CsvWriteStrategy constructor -> delimiter/charset/header flag
-> setCatalogTable -> CsvSerializationSchema with same delimiter/charset
-> beginTransaction -> write -> partition/file path -> getOrCreateOutputStream
-> new file stream -> enableWriteHeader -> configured header bytes + newline
-> row serialization/write using same charset -> finishAndCloseFile
-> close/record pending move -> existing sink commit/checkpoint handling
This is a precise shared file-writer fix; no engine/source or serializer-state change is needed. Header quoting/projection redesign and BOM-policy changes are outside this two-line correction; the tests do not claim to cover arbitrary CSV naming/encoding contracts.
1.2 Compatibility Impact
Compatible with the documented delimiter/encoding contract: names/defaults, APIs/SPI and checkpoint format are stable. Header bytes intentionally change for non-default delimiter/charset configurations. Consumers that worked around the malformed old header should be told about that correction (Issue 1); no incompatible config migration is introduced.
1.3 Performance / Side-Effect Analysis
Per-file header joining/encoding remains O(columns/header bytes), with an explicit charset instead of platform lookup. No added per-row allocation, thread, network round trip, lock, retry, global state or resource lifetime. Memory/GC and concurrency behavior are unchanged; transactions/idempotency are not redesigned.
1.4 Error Handling and Logging
Header I/O exceptions still reach the existing file-open error wrapper with file context. No exception is swallowed by this patch and no new payload/credential logging is introduced.
+1 to @LiJie20190102's earlier request for a non-comma integration case (existing comment). The added unit cases now prove default comma, multi-character delimiter and UTF-16LE values. However, the existing LocalFileIT.testLocalFileCsv (:379-385) and its configs are unchanged, so the earlier E2E request and repository requirement to update the existing connector IT are not yet met. Please extend that existing case/config with header writing and a non-comma delimiter, asserting the actual header and row values through the integrated file path. I am keeping this under the existing reviewer's point, rather than creating a duplicate Daniel issue.
Issue 1: Add matching CSV header guidance in EN/ZH
- Location:
docs/en/connectors/sink/LocalFile.md:field_delimiter/enable_header_write/encoding; matchingdocs/zh/connectors/sink/LocalFile.md(unchanged). - Problem: this is user-visible output correction, but the docs do not state that header bytes now honor delimiter/encoding. The Chinese option table also still describes field_delimiter as text-only while the English page correctly includes CSV.
- Risk: users retain a workaround for comma headers or follow inconsistent language guidance for custom CSV delimiters.
- Best improvement: add a matching short header example/note in both languages and align the Chinese delimiter scope with text/csv. Keep option names/defaults unchanged.
- Severity: Medium, required before merge under the user-visible documentation rule.
- Raised by another reviewer: No paired-header-doc point in the fetched reviews.
2. Code Quality Assessment
2.1 Coding Standards
Minimal production edit, existing test class extended, required import restored, helpers document the lifecycle and mock seam. No new dependency/file/plugin mapping. The setter-style injection helpers are straightforward test plumbing.
2.2 Test Coverage and Test Stability
Stability rating: Stable for added CsvWriteStrategyTest.java:60-144 cases: synchronous in-memory Hadoop stream, explicit UTF-8/UTF-16LE, exact header/row strings and deterministic values; no real host port, filesystem or clock. Closing ByteArrayOutputStream still permits reading its contents. Decoding with the same configured charset makes platform-encoded headers fail the non-ASCII test. Existing source-reader tests/assertions are preserved. Required integrated coverage remains with @LiJie20190102's point above.
Local evidence: exact fetch/checkout seatunnel-review-10257; complete diff read; numbered/rg traces of constructor/config, serialization, stream/header creation, file close/transaction and test injection; git diff --check upstream/dev...HEAD passed. No local compile, UT/IT/E2E, service or real job execution.
Current CI is not the historical Maven Central failure. Exact-head fork Build is CANCELLED. The sole non-success/non-skipped lane is connector-file-local-it (11); GitHub explicitly annotates The job has exceeded the maximum execution time of 2h0m0s. It was cancelled while issuing an ORC read/assert job, not on a reported CSV header assertion. Latest dev retains the same 120-minute lane budget, so syncing is not a demonstrated cure. A maintainer should rerun only that cancelled lane; a recurring shared-lane duration problem belongs in a separate CI investigation, not an unrelated timeout patch here. The Apache PR signal separately awaits workflow approval. Neither cancellation nor signal approval is a passing runtime test.
2.3 Documentation Updates
Issue 1 requires the paired header note and consistent delimiter scope. There is no new option or default to migrate.
3. Architectural Soundness
3.1 Elegance
Precise fix where header bytes are emitted. Smallest safe and best location coincide: reuse the writer's already-resolved delimiter/charset, rather than modify shared CSV row serialization or compensate in the reader.
3.2 Maintainability
Header and rows use one configuration contract; lifecycle/resource behavior stays localized.
3.3 Extensibility
The shared strategy applies the correction to its existing file sinks without connector-specific engine logic.
3.4 Historical-Version Compatibility
Stable configs/state; corrected bytes for custom header configurations should be explained to users relying on the old inconsistency.
4. Issue Summary
Full diff, config/writer/transaction path, output contract, resources, test strength/stability, docs, existing reviewer points and CI checked.
| Number | Issue | Location | Severity |
|---|---|---|---|
| LiJie20190102 existing integration point (+1) | Existing connector IT still lacks non-comma header coverage | LocalFileIT.java:379-385 and CSV configs |
Medium, required |
| 1 | Missing paired header note / inconsistent Chinese delimiter scope | EN/ZH LocalFile sink docs | Medium, required |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers (must resolve): the existing integration-test point, Issue 1, the cancelled runtime lane/workflow-approval gate, and write-capable maintainer approval.
- Recommended fixes (non-blocking): none beyond those focused items; no broader CSV or workflow refactor is needed.
Overall, I agree with @chl-wxp's assessment that this fixes a real subtle header inconsistency, and with the existing requests for meaningful non-comma test coverage. The unit/import/formatting issues from earlier rounds are addressed. Compare is dev diverged, ahead 10 / behind 2, without conflict. Drift is recorded only; the current timeout has no verified upstream sync-first fix. GitHub remains BLOCKED / REVIEW_REQUIRED. This COMMENT is not an effective approval or a successful cancelled job.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the fix, @jiamin13579, and thanks to everyone who carried it through. The new head (79d09069e0) adds the paired EN/ZH docs and a real LocalFile integration case on top of the already-reviewed production fix, which closes the two required items from my previous review. I re-read the whole 6-file diff from scratch and re-traced the writer path at this head. This is a code-reading review only; nothing was executed locally.
What Problem Does This PR Solve?
- User pain point: for the File Sink CSV writer, data rows honor
field_delimiterandencoding, but the header line was hardcoded to a comma and encoded with the JVM platform default charset, so header and rows could disagree. - Fix approach: write the header (and its row delimiter) with the same configured delimiter and charset as the data rows.
- One sentence: make a CSV header agree with its own file's rows.
1. Code Change Review
1.1 Core Logic Analysis
Production change is the same two lines as before: CsvWriteStrategy.java:185-191.
Before:
stream.write(String.join(",", seaTunnelRowType.getFieldNames()).getBytes());
stream.write(rowDelimiter.getBytes());After:
stream.write(String.join(fieldDelimiter, seaTunnelRowType.getFieldNames()).getBytes(charset));
stream.write(rowDelimiter.getBytes(charset));Key findings:
- Only reached when
enable_header_write=true(defaultfalse), once per newly opened file in each compress branch (LZO / NONE / default), so the default behavior is unchanged. fieldDelimiterandcharsetare resolved in the constructor fromFileSinkConfig, and the same values feedCsvSerializationSchemaand the row-delimiter write inwrite(); the header now uses the identical contract. After the header,isFirstWritesuppresses the leading row delimiter for row 1, so the file isheader\nrow1\nrow2with no trailing newline, exactly what the new IT asserts.
Runtime path:
FileSinkConfig -> CsvWriteStrategy ctor (fieldDelimiter, charset, header flag)
-> setCatalogTable -> CsvSerializationSchema (same delimiter/charset)
-> write() -> getOrCreateOutputStream -> new file -> enableWriteHeader
-> rows via same charset -> finishAndCloseFile -> needMoveFiles -> sink commit
1.2 Compatibility Impact
Partially incompatible, in the intended direction: names, defaults, APIs/SPI and checkpoint state are unchanged, but the header bytes change for jobs that use a non-comma field_delimiter or a non-default encoding with enable_header_write=true. Any consumer that worked around the old comma/platform-encoded header must adjust. The new EN/ZH docs state this explicitly, which is the right mitigation for a bug fix of this kind.
1.3 Performance / Side-Effect Analysis
Per-file header join/encode only, with an explicit charset instead of a platform lookup. No per-row cost, thread, lock, retry or resource lifetime change.
1.4 Error Handling and Logging
Header I/O errors still surface through the existing fileOperationFailed("CsvFile", "open", ...) wrapper. Nothing is swallowed, nothing new is logged.
Issue 1: Header ignores sink_columns projection while rows honor it (pre-existing, non-blocking)
- Location:
CsvWriteStrategy.java:187(seaTunnelRowType.getFieldNames()) versusCsvWriteStrategy.java:76-82andAbstractWriteStrategy.buildSchemaWithRowType(:165-179). - Problem: data rows are serialized with a schema projected through
sinkColumnsIndexInRow, but the header lists every field of the full row type. Withsink_columnsset, the header would have more columns than the rows. - Risk: same "header does not match rows" symptom this PR targets, for a different option. It exists before this PR and is not made worse by it.
- Best improvement: either a small follow-up using
buildSchemaWithRowType(seaTunnelRowType, sinkColumnsIndexInRow).getFieldNames()for the header, or a separate issue. I do not consider it a blocker for this PR. - Severity: Medium, non-blocking.
- Raised by another reviewer: No.
Issue 2: IT assumes an empty output directory (robustness)
- Location:
LocalFileIT.javatestLocalFileCsv,countLocalFiles("/tmp/csv/header_utf16", "*.csv") == 1. - Problem: nothing removes
/tmp/csv/header_utf16before the job or afterwards (other tests in this class userm -rfon their directories). A rerun of the test in the same container would produce a second transaction-named file and the count assertion would fail. - Risk: only flakiness on re-execution; the assertion itself is meaningful.
- Best improvement: run
rm -rf /tmp/csv/header_utf16beforehelper.execute(...)(and optionally after), mirroring the existing cleanup calls. - Severity: Low.
- Raised by another reviewer: No.
2. Code Quality Assessment
2.1 Coding Standards
Minimal production edit; the existing test class and existing IT are extended; the new conf has the ASF header; test helpers have Javadoc explaining the lifecycle and mock seam. No new dependency.
2.2 Test Coverage and Test Stability
CsvWriteStrategyTestheader cases (default comma,||, UTF-16LE): Stable. In-memory Hadoop stream, exact strings, same-charset decoding so a platform-charset header would fail the non-ASCII case; reverting the fix makes the||and UTF-16LE cases fail.LocalFileIT.testLocalFileCsvaddition: Stable apart from Issue 2. It runs a real FakeSource-to-LocalFile job (two custom rows,parallelism=1, no sleeps or polling) and compares the complete committed bytes (headerid||<CJK name>plus two CJK-valued rows joined by\n) against the expected UTF-16LE encoding, so a comma or platform-charset header fails it. All five earlier scenarios in the test are retained, so no weakening.- Earlier requests from @zhangshenghang (add a test class) and @LiJie20190102 (non-comma delimiter in E2E) are now met.
2.3 Documentation Updates
Done. EN LocalFile.md and ZH LocalFile.md both have the same header note with the || and UTF-16LE examples, and the ZH option table/section now lists csv for field_delimiter, matching EN.
3. Architectural Soundness
- Fix type: Precise fix, at the single place header bytes are emitted.
- Maintainability: header and rows now share one configuration contract.
- Extensibility: the shared strategy fixes every file sink that reuses it, without connector-specific logic.
- Historical compatibility: configs and state are unchanged; see 1.2 for the intended byte change.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Header ignores sink_columns projection (pre-existing) |
CsvWriteStrategy.java:187 |
Medium, non-blocking |
| 2 | IT assumes empty output dir | LocalFileIT.java testLocalFileCsv |
Low |
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers: none from the code side. CI has not run for this head yet (see below), and a write-capable maintainer approval is still required.
- Recommended non-blocking fixes: Issue 1 (can be a follow-up) and Issue 2.
CI status: there is no Build check on this head, and I could not find GitHub Actions runs for it in the fork either. The only check is the "PR signal" run, which is waiting for workflow approval: https://github.com/apache/seatunnel/actions/runs/40308038670. Please make sure GitHub Actions workflows are enabled in your fork (Actions tab, "I understand my workflows, go ahead and enable them") and re-trigger, or ask a maintainer to approve the workflow run, so the real Build can run. The Build result is required before merge; this COMMENT is not a runtime pass.
Overall: a small, correct and well-tested fix with the docs and integration coverage now in place.
|
Good job. Thanks a lot for your valuable contribution to Apache SeaTunnel! To pass the automated CI checks for this PR, could you please enable CI workflows in your forked repository first? You can refer to the check run link below as a reference for the required CI configuration https://github.com/apache/seatunnel/actions/runs/40314938242 If you run into any trouble enabling CI or encounter related errors during the process, feel free to leave a comment here. Contributors are always ready to offer help~
|
|
Thanks for the workflow reminder. My existing source conclusion on this unchanged head remains clear; the remaining CI issue is obtaining an actual exact-head fork Build and attaching its result. A missing run does not on its own prove that Actions is disabled, so check that setting and otherwise dispatch the existing Build workflow for this branch. There is no reason to add unrelated source changes or an empty commit merely to investigate that activation gate. Gate snapshot (2026-10-28T16:00:58+00:00), head The exact blocking stage is Build workflow-run detection: the check says no fork Build was found for this SHA. This is not an executed test failure and does not by itself prove that fork Actions is disabled. Open the fork Actions tab, enable workflows if needed, then manually run the existing Build workflow for this PR branch. If a matching run already exists, link it for a maintainer to reconcile the aggregate. No empty commit or speculative dependency change is requested. Upstream check: current dev retains the fork-run adoption workflow and its scheduled/manual status-refresh path. A base sync alone cannot enable fork Actions or supply a missing exact-head workflow run, so I am not prescribing sync as the fix for this activation gate. My previous source conclusion remains clear for the reviewed scope. CI is not being passed by inference, and this follow-up is not an effective approval. Comparison recorded in this scan: base |
|
Thanks for keeping this contribution moving. I need to update the merge-gate information on unchanged head Please sync the latest My latest source conclusion remains clear. A matching exact-head fork Build still needs to be supplied/adopted; resolving a content conflict does not itself enable or execute Actions. The preceding complete source review remains the source assessment; this is a gate clarification, not another full review or a new list of source findings. Current existing-head checks: Build=ACTION_REQUIRED. Compare |

Purpose of this pull request
Does this PR introduce any user-facing change?
How was this patch tested?
Check list
New License Guide
incompatible-changes.mdto describe the incompatibility caused by this PR.