Repository navigation
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
What Problem This PR Solves
- User pain point
When a JSON record omits a field or sendsnull, the current JSON deserializer leaves the SeaTunnel row field asnulleven if the catalog column declares a default value. - Fix approach
This PR readsColumn.defaultValuefrom the catalog schema and applies it when the converted JSON field result isnull. - One-sentence summary
The goal is to make JSON source deserialization honor catalog column defaults for missing or null fields.
I. Code Change Review
1.1 Core Logic Analysis
Exact change description
The core changes are in:
seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonDeserializationSchema.java:105-122seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonToRowConverters.java:81-95seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonToRowConverters.java:422-428
Before / after snippets
Before:
this.runtimeConverter =
new JsonToRowConverters(failOnMissingField, ignoreParseErrors)
.createRowConverter(checkNotNull(rowType));After:
Object[] defaultValues = ... columns.get(i).getDefaultValue();
this.runtimeConverter =
new JsonToRowConverters(failOnMissingField, ignoreParseErrors, defaultValues)
.createRowConverter(checkNotNull(rowType));Before:
Object convertedField = convertField(fieldConverters[i], fieldName, field);
row.setField(i, convertedField);After:
Object convertedField = convertField(fieldConverters[i], fieldName, field);
if (convertedField == null && defaultValues != null && i < defaultValues.length
&& defaultValues[i] != null) {
convertedField = defaultValues[i];
}
row.setField(i, convertedField);Key findings
- The normal JSON-to-row path will hit this change immediately in connectors that construct
JsonDeserializationSchemafrom aCatalogTable. - The PR injects catalog defaults after conversion, but it does not convert the default value through the field's runtime converter.
- Existing API evidence already shows catalog defaults are not always stored in the final SeaTunnel runtime type.
- So the fix only works when
Column.defaultValuealready happens to be in the target runtime type; it is incorrect for typed defaults such as dates/timestamps represented as strings.
Deep logic analysis
The execution path here is:
JSON source connector
-> new JsonDeserializationSchema(catalogTable, ...)
-> JsonDeserializationSchema extracts Column.defaultValue from catalog schema
-> passes raw defaultValues[] into JsonToRowConverters
Row conversion
-> JsonToRowConverters.createRowConverter()
-> convertField(fieldConverters[i], fieldName, field)
-> if result is null, directly assign defaultValues[i]
-> SeaTunnelRow.setField(i, convertedField)
The bug is in the last step: defaultValues[i] is assigned as-is, without going through the same type-specific conversion logic used for JSON field values.
That is observable from existing parser coverage in seatunnel-api/src/test/java/org/apache/seatunnel/api/table/catalog/schema/ReadonlyConfigParserTest.java:263-268, where a date default is still stored as the string "2020-01-01" rather than a LocalDate. With this PR, a JSON date field that is null/missing would therefore put a String into a DATE column slot of SeaTunnelRow, which violates the row type contract and can break downstream operators that expect the runtime type.
Full execution path
Connector source reads JSON
-> JsonDeserializationSchema(CatalogTable, failOnMissingField, ignoreParseErrors)
-> JsonDeserializationSchema.java:109-118 collects Column.defaultValue
-> JsonToRowConverters(..., defaultValues).createRowConverter(rowType)
Per-field conversion
-> JsonToRowConverters.createRowConverter()
-> jsonNode.get(fieldName)
-> convertField(fieldConverters[i], fieldName, field)
-> normal path converts JSON into runtime field type
-> PR-added fallback at JsonToRowConverters.java:423-428
-> if convertedField == null, assign raw defaultValues[i]
Risk window
-> Column.defaultValue can still be a config-level literal
-> ReadonlyConfigParserTest.java:268 shows a DATE default stored as \"2020-01-01\"
-> PR bypasses type conversion for that fallback
-> SeaTunnelRow gets a String in a DATE/TIMESTAMP/other typed slot
Local verification results used for this review:
gh pr view 11634 --json ...: completed, used to confirm the latest head (c070511e06f3d2ef6585383501f1064287e2a93f) and current checks.gh api repos/apache/seatunnel/compare/dev...c070511e06f3d2ef6585383501f1064287e2a93f: completed, current compare status isahead,ahead_by=2,behind_by=0.gh api repos/apache/seatunnel/commits/c070511e06f3d2ef6585383501f1064287e2a93f/check-runs: completed. TheBuildcheck isaction_requiredwith titleWorkflow run detection failed.git diff upstream/dev...seatunnel-review-11634 -- <files>: completed for the full changed set.- Build / unit tests / E2E execution: not run locally. Per this batch's SeaTunnel review rule, I relied on source analysis and current GitHub check state.
1.2 Compatibility Impact
Judgment: Partially incompatible
Impacts:
- API: no public API signature change.
- Configuration: no config key change.
- Default behavior: yes, but the new behavior is not type-safe for every column type.
- Protocol: no protocol change.
- Serialization format: no direct byte-format change, but the runtime
SeaTunnelRowfield type can become inconsistent with the declared schema. - Historical behavior: downstream code that assumes typed row fields can now receive raw config literals when defaults are used.
1.3 Performance / Side-Effect Analysis
- CPU / memory / GC: negligible overhead from the fallback lookup itself.
- Network: no direct impact.
- Concurrency safety: unchanged.
- Retry / idempotency: unchanged.
- Resource release: unchanged.
- Main side effect: schema-typed row fields can now silently carry raw config literal objects instead of runtime-converted values.
1.4 Error Handling and Logging
Issue 1: Default values are injected without type conversion
- Location:
seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonDeserializationSchema.java:108-122seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonToRowConverters.java:422-428- supporting evidence:
seatunnel-api/src/test/java/org/apache/seatunnel/api/table/catalog/schema/ReadonlyConfigParserTest.java:263-268
- Problem description:
The PR collectsColumn.defaultValuefrom the catalog schema and assigns it directly when a field converts tonull, but it never passes that fallback through the field's runtime converter. In current SeaTunnel code, catalog defaults are not guaranteed to already be stored in the final runtime type. For example, the existing parser test shows a date default still stored as the string"2020-01-01". That means this fix can place a raw string into aDATEorTIMESTAMPfield ofSeaTunnelRow. - Potential risk:
Downstream transforms/sinks can observe row values whose runtime Java type no longer matches the declared schema. That is a real correctness issue on the main deserialization path. - Best improvement suggestion:
Apply the default through the same field-specific converter path instead of assigning the raw catalog object. For typed literals, that likely means converting from the config literal representation into the row runtime type beforerow.setField(i, ...). - Severity: High
- Already raised by others: No
Issue 2: The current Build gate is blocked because no runnable workflow was detected for this fork head
- Location:
- Build check:
https://github.com/apache/seatunnel/runs/91706443832
- Build check:
- Problem description:
The currentBuildcheck isaction_requiredwith the GitHub messageWorkflow run detection failed, which means the PR still does not have a runnable current-head backend workflow result. - Potential risk:
Even after the source fix above, the PR still cannot merge until the contributor-side workflow gate is restored. - Best improvement suggestion:
Please enable GitHub Actions in the fork if they are currently disabled, then push an empty commit to retrigger the workflow. Since this branch is not behinddev(behind_by=0), the immediate next step is the workflow enable/retrigger path rather than a sync-first instruction. - Severity: High
- Already raised by others: No
II. Code Quality Assessment
2.1 Coding Standards
The added comments in JsonDeserializationSchema explain the physical-column alignment clearly. The style is consistent overall.
2.2 Test Coverage and Test Stability
I do not see any new regression test covering the key typed-default path on JsonDeserializationSchema(CatalogTable, ...), even though this PR changes a deserialization contract. Existing tests already exercise that constructor (JsonRowDataSerDeSchemaTest.java:186-188), so this change should add coverage there for at least one typed default such as DATE or TIMESTAMP.
Test stability conclusion: Stable
- No UT/E2E code was changed in this PR, so I did not find a new flaky-test pattern introduced here.
2.3 Documentation Updates
No user-facing documentation update is needed if the implementation is fixed in place, because this is a bug fix to existing default-value behavior rather than a new feature contract.
III. Architecture Rationality
3.1 Elegance of the Solution
The intent is precise, but the current implementation stops one step too early: it adds a fallback value without integrating it into the existing type-conversion path.
3.2 Maintainability
The fallback hook is small and localized, which is good. The maintainability issue is correctness: future readers could assume defaultValues[i] is already safe for the row runtime type, but the current API does not guarantee that.
3.3 Extensibility
Once fixed through the existing converters, this can become a reusable default-value mechanism for more JSON-based sources. In its current raw-assignment form, it is brittle across more data types.
3.4 Historical Version Compatibility
This should remain backward compatible as a bug fix, but only after the default fallback is converted into the declared runtime type.
IV. Issue Summary
Blocker Exhaustiveness Self-Check
- Full changed diff reviewed.
- Main deserialization call chain traced from
JsonDeserializationSchema(CatalogTable, ...)intoJsonToRowConverters.createRowConverter(). - Current CI gate reviewed separately from source findings.
- No second source-side blocker beyond the raw default-type injection was found in this version.
| No. | Issue | Location | Severity |
|---|---|---|---|
| 1 | Default values are injected without type conversion | JsonDeserializationSchema.java:108-122; JsonToRowConverters.java:422-428 |
High |
| 2 | Current Build gate is still action_required for this fork head |
https://github.com/apache/seatunnel/runs/91706443832 |
High |
V. Merge Recommendation
Conclusion: Can be merged after fixes
- Blocking items (must fix)
- Issue 1: convert catalog defaults into the field runtime type before inserting them into
SeaTunnelRow. - Issue 2: enable/retrigger the contributor-side workflow so the current head gets a runnable Build result.
- Suggested improvements (non-blocking)
- Add a regression test in
JsonRowDataSerDeSchemaTestthat covers typed defaults on theCatalogTableconstructor path.
Overall assessment:
The direction makes sense, but the current implementation is not yet safe for typed defaults, and the PR still lacks a runnable current-head Build workflow.
Better alternative implementation:
- Reuse the existing field-specific conversion path for default literals instead of assigning the raw
Column.defaultValueobject.
|
Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here! Please ignore the following message if you have joined in the Slack~ |
…converter and cover typed defaults Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
|
Pushed
Your fork did not create a Build run for this push; if none appears, please start one from the Actions tab ("Run workflow" on Build). Verification run of the same head on my fork: https://github.com/DanielLeens/seatunnel/actions?query=branch%3Apr11634-verify-4e85efec792 |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for working on this, @waterWang! I went through the full diff against the latest head (4e85efe). The typed-default problem from my previous review (Issue 1 there) is fixed: the default is now converted through the field converter, and the new test covers INT, DECIMAL and STRING defaults.
An apology first: on this second pass, tracing every caller of JsonToRowConverters and JsonDeserializationSchema(CatalogTable, ...) turned up problems that I should have caught the first time (nested rows, changelog formats, parse-error masking). I am raising them all at once now, so you do not get another round of drip-fed feedback.
What Problem Does This PR Solve?
- Pain point:
schema.columns[].defaultValueis parsed intoColumnbut never applied by the JSON deserializer, so a missing ornullJSON field staysnull(issue #11632). - Fix approach:
JsonDeserializationSchema(CatalogTable, ...)collects the physical-column defaults and passes them toJsonToRowConverters, which substitutes the default (converted through the same field converter) when the converted field isnull. - Summary: honor catalog column defaults for missing or null JSON fields.
- Example: column
qty INT defaultValue=7, input{"id":1}->qty = 7instead ofnull.
1. Code Change Review
1.1 Core Logic Analysis
Runtime path (normal path hits the change for every connector that builds JsonDeserializationSchema from a CatalogTable, and for Canal and Ogg):
Source reader (Kafka, Http, Pulsar, file json, ...)
-> JsonDeserializationSchema(CatalogTable, failOnMissingField, ignoreParseErrors) JsonDeserializationSchema.java:105-121
builds defaultValues[] indexed by PHYSICAL column position
-> new JsonToRowConverters(failOnMissingField, ignoreParseErrors, defaultValues)
.createRowConverter(rowType) JsonToRowConverters.java:410
-> per record: row converter loop JsonToRowConverters.java:437-466
convertField(...) == null && defaultValues[i] != null
-> convertField(fieldConverters[i], name, TextNode.valueOf(String.valueOf(default)))
Before: row.setField(i, convertField(...)). After: same, plus the default fallback shown above.
1.2 Compatibility Impact
Partially compatible. No config key or public signature changes (the 2-arg constructor is kept). Behavior changes for existing jobs that declared defaultValue (previously silently ignored): their nulls now become defaults. That is the intent of the fix, but see Issues 2 and 3 for places where it is not wanted, and Issue 6 for the missing documentation.
1.3 Performance / Side-Effect Analysis
See Issue 4: the default is re-parsed from a string for every record that has a null field.
1.4 Error Handling and Logging
Issue 1 (High): nested ROW converters reuse the top-level defaultValues array
- Location:
JsonToRowConverters.java:225(case ROW: return createRowConverter(...)),:410-466,:84-96; array/map element converters at:478-494. - Problem:
defaultValuesis an instance field ofJsonToRowConverters, butcreateRowConverteris also called recursively for nestedROWcolumns (and forARRAY<ROW>/MAP<_, ROW>elements) on the same instance. Every returned row converter readsdefaultValues[i]with its own local indexi. The array was built from the TOP-LEVEL columns only. - Concrete example: schema
id INT defaultValue=0, addr ROW<city STRING, zip INT>. For{"id":1,"addr":{"zip":5}}, the nested converter seescitymissing at index 0 and appliesdefaultValues[0](the default of top-levelid), soaddr.city = "0". With a top-level default on column 1, nested index 1 (zip) would also be overwritten whenzipis null. - Risk: silent data corruption for any job that has both a column default and a nested row type. The new test only covers a flat schema, so it stays green.
- Best improvement: apply defaults only in the top-level row converter. For example, keep the default handling out of the recursive
createRowConverter(pass the defaults to a dedicated top-level creation method, or wrap the top-level converter inJsonDeserializationSchema), so nested converters are built without defaults.
Issue 2 (High): changelog formats now replace genuine NULLs with defaults
- Location:
canal/CanalJsonDeserializationSchema.java:105-106,244,ogg/OggJsonDeserializationSchema.java:103-104(both buildnew JsonDeserializationSchema(catalogTable, false, ignoreParseErrors)and callconvertToRowData(...)ondataimages); Debezium builds the same object atdebezium/DebeziumJsonDeserializationSchema.java:86-87. - Problem: in a change-log message a
nullcolumn is a real database value (including the old image of UPDATE/DELETE events). With this PR, if the schema hasdefaultValue, Canal/Ogg rows now carry the default instead ofnull. I verified Canal and Ogg's use ofconvertToRowData; for Debezium I only confirmed it constructs the same schema object and did not trace its full row path, so please treat that part as unverified. - Risk: a row replicated downstream differs from the source row, and delete/update-by-full-row matching can miss. This is an inference from the call sites, not something I could run.
- Best improvement: make default application an explicit behavior of the plain JSON source path only (for example a constructor flag that the changelog formats do not enable), or confirm and document that changelog formats must not declare defaults.
Issue 3 (Medium): ignoreParseErrors=true now turns bad values into defaults, and failOnMissingField=true never reaches the default
- Location:
JsonToRowConverters.java:449-463and:538-557(wrapIntoNullableConverterreturnsnullon a swallowed parse error). - Problem: the condition is "converted value is null", which is also true for a PRESENT but unparsable value when
ignoreParseErrors=true(for example"qty":"abc"). That value was previouslynull(explicitly "ignored"), and is now silently replaced with the default, hiding bad data. Conversely, withfailOnMissingField=true,convertFieldthrows on a missing field before the default is considered, so the default only applies to explicitnulls there. - Best improvement: apply the default only when the JSON field is absent or is a JSON null (check
field == null || field.isNull()rather than the converted result), and document thefailOnMissingFieldinteraction.
Issue 4 (Medium): per-record allocation and re-parsing, and late failure on invalid defaults
- Location:
JsonToRowConverters.java:454-462. - Problem: for every record with a null field, a
TextNodeis allocated and the default string is parsed again (decimals, dates, timestamps with formatters). At the batch/stream volumes SeaTunnel targets this is avoidable CPU and garbage on the hot path. Also, an unparsable default (for example a DB expression such asCURRENT_TIMESTAMP) is only discovered when the first null arrives, and withignoreParseErrors=falseit fails the job at that point instead of at startup. Mutable defaults (BYTES) would also be shared if cached naively. - Best improvement: convert each default once when the converter is created (fail fast with a clear message naming the column), cache the immutable result, and copy for
byte[].
Issue 5 (Low): String.valueOf(defaultValue) is lossy for non-string defaults such as byte[], and complex types (ARRAY/MAP/ROW) cannot be built from a TextNode. Consider rejecting defaults on unsupported types at construction time.
2. Code Quality Assessment
2.1 Coding Standards
The comments explain why (physical-column alignment, typed conversion). The field defaultValues is documented; consider also documenting on the constructor that the array must be top-level only, once Issue 1 is fixed.
2.2 Test Coverage and Test Stability
JsonRowDataSerDeSchemaTest.testCatalogColumnDefaultsAreTypedWhenFieldMissingOrNull is a good regression test for the typed-default path (it fails if the default is stored as the raw string, because the Integer / BigDecimal assertions would break). Gaps:
- no nested ROW or ARRAY case (would expose Issue 1),
- no
ignoreParseErrors=truecase (Issue 3), - no non-physical (computed/metadata) column before a physical one to prove the index alignment,
- no Canal/Ogg case (Issue 2).
Stability: Stable (no sleeps, ports, shared state, or order dependence in the new test).
2.3 Documentation Updates
docs/en/introduction/concepts/schema-feature.md:134 only says "The default value of the column", with no docs/zh counterpart touched. Because this changes runtime behavior for existing configs, please document that JSON-based sources now apply defaultValue for missing/null fields, with the failOnMissingField and changelog-format caveats, in docs/en and docs/zh.
3. Architectural Soundness
3.1 Elegance
The goal is right, but the mechanism (a positional array stored on the shared converter factory) is fragile. It is a precise fix for flat schemas only; keeping the defaults scoped to the top-level row (or resolved per column once) would be the sturdier long-term shape.
3.2 Maintainability / 3.3 Extensibility
Positional coupling between CatalogTable physical columns and the converter is implicit; a column-name-keyed or pre-resolved structure would survive schema changes better.
3.4 Historical-Version Compatibility
No serialization or checkpoint format is touched. The behavior change is limited to jobs that already declare defaultValue.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Nested ROW converters reuse the top-level defaults by index | seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonToRowConverters.java:225,410-466 | High |
| 2 | Changelog formats (Canal/Ogg, and Debezium to be confirmed) turn real NULLs into defaults | canal/CanalJsonDeserializationSchema.java:105,244; ogg/OggJsonDeserializationSchema.java:103 | High |
| 3 | ignoreParseErrors masks bad values with defaults; failOnMissingField interaction undocumented |
JsonToRowConverters.java:449-463 | Medium |
| 4 | Default re-parsed per record; invalid default fails late | JsonToRowConverters.java:454-462 | Medium |
| 5 | String.valueOf is lossy for non-string/complex defaults |
JsonToRowConverters.java:462 | Low |
| 6 | Docs (en and zh) and tests for the new behavior are missing | docs/en/introduction/concepts/schema-feature.md:134 | Medium |
5. Merge Recommendation
Conclusion: Not recommended for merge
Blockers:
- Issue 1 (nested row corruption) and Issue 2 (changelog formats), each with a regression test.
- Issue 3 (do not apply defaults on swallowed parse errors).
- CI: all checks on this head are still queued (
Build,labeler,Notify test workflow); the fork did not start a Build run for the latest push, so please start it from the Actions tab of your fork. I could not run the tests myself; they are verified only by GitHub CI.
Recommended non-blocking fixes: Issues 4, 5 and 6.
Overall assessment: the fix direction is right and the typed-default handling is now correct for flat schemas, but the shared positional array makes it unsafe for nested rows and for changelog formats, which are exactly the kind of silent data-correctness issues that are hard to detect in production. Alternatives: resolve defaults per top-level column once at construction, and apply them only in the plain JSON source path.
Note for transparency: commit 4e85efe was pushed onto this branch by a maintainer account (DanielLeens), so the typed-conversion part of this head is not your code; the issues above apply to the combined head.
|
Thanks @waterWang. A quick correction to the CI note in my last review: I said all checks on this head were still queued, but the fork has since run the
Next step for CI: this branch is now 12 commits behind |
What problem does this PR solve?
Issue Number: close #11632
Problem Summary
When a source connector using the JSON format (Kafka, Pulsar, HTTP, etc.) configures
schema { columns = [ { name = "GROUPID", type = "int", defaultValue = 0 } ] }, thedefaultValueis parsed and stored on theColumnbut never applied during deserialization: if the JSON message is missing the field or contains an explicitnull, the row field staysnullinstead of the configured default value.Root Cause
The
defaultValueis lost on the way fromCatalogTableto the row converter:CatalogTable.getSeaTunnelRowType()callstoPhysicalRowDataType(), which creates aSeaTunnelRowTypewith onlyfieldNames[]andfieldTypes[]— thedefaultValueis dropped.JsonToRowConvertersbuilds converters fromSeaTunnelRowTypeand has no access toColumnmetadata.convertField()encounters anullor missing field, it returnsnullwithout consulting the default value.What Changed
JsonToRowConverters: Added an optionaldefaultValuesarray parameter. When a field isnull/missing and a non-null default value exists for that column, the default value is used instead ofnull.JsonDeserializationSchema: Extracts default values fromCatalogTable.getTableSchema().getColumns()(filtering to physical columns to matchtoPhysicalRowDataType()behavior) and passes them to the converters.How was this tested?
defaultValuesarray isnullby default, preserving backward compatibility).defaultValue = 0/defaultValue = "unknown") now correctly applies defaults when fields are missing ornull.