Repository navigation
[Feature] [Transform-V2] Add UNIX_TIMESTAMP SQL function - #12703
Conversation
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for taking this on, and for keeping the whole change (code, unit tests, E2E, EN/ZH docs) in one focused PR. I read the full diff of head d26d794d80a1 and traced the function through the Zeta SQL engine. I found no blocking issue. There are two medium items that I would like to see addressed or consciously accepted, and a few low ones.
What Problem Does This PR Solve?
- User pain point: Hive / Spark SQL jobs that use
UNIX_TIMESTAMPcannot be moved to the Zeta SQL transform; today users have to rewrite them withPARSEDATETIMEplus manual epoch arithmetic (#12699). - Fix approach: register
UNIX_TIMESTAMPinZetaSQLFunction(constant + dispatch case), resolve its type asLONGinZetaSQLType, and implementDateTimeFunction.unixTimestampfor three forms: no argument (now), a typed datetime (LocalDateTime/LocalDate/OffsetDateTime), and a string with an optional pattern (defaultyyyy-MM-dd HH:mm:ss). Parse failures return NULL. - One-sentence summary: the inverse of the existing
FROM_UNIXTIME, added as a pure addition.
1. Code Change Review
1.1 Core Logic Analysis
Changed production code: ZetaSQLFunction.java (constant at :203, dispatch case at :626), ZetaSQLType.java (added to the LONG_TYPE group next to DATEDIFF / MURMUR64), DateTimeFunction.unixTimestamp (:823-866).
Sql transform row
-> ZetaSQLFunction.computeForValue(Function) args evaluated left to right
-> executeFunctionExpr("UNIX_TIMESTAMP", args) :626 (built-in switch comes BEFORE the UDF loop at :686)
-> DateTimeFunction.unixTimestamp(args)
args empty -> Instant.now().getEpochSecond()
arg0 == null -> null
OffsetDateTime -> toEpochSecond() (own offset)
LocalDateTime/LocalDate -> atZone(ZoneId.systemDefault())
else toString() + (pattern | default) -> DateTimeFormatter.parseBest(LocalDateTime, LocalDate)
DateTimeException -> null ; invalid pattern -> IllegalArgumentException (documented)
-> output type: ZetaSQLType -> BasicType.LONG_TYPE
Key findings:
- The normal path (a SQL transform containing the function) reaches every new line; there is no boundary-only code.
- The time zone contract the maintainers asked about on the issue is explicit now: local datetimes and strings use the JVM default zone (same default as
FROM_UNIXTIMEwithout a zone argument),OffsetDateTimeuses its own offset. This is documented in both docs and in the Javadoc. - NULL handling is consistent: NULL value gives NULL, explicit NULL pattern gives NULL, unparseable string gives NULL, numeric input gives NULL (it is stringified and fails the default pattern).
- Zero-argument functions already work in this engine (
NOW(),UUID()), soUNIX_TIMESTAMP()needs no special parser handling.
1.2 Compatibility Impact
Fully compatible: pure addition, no option or default change, no serialization impact. One small note in Issue 5: the built-in switch is evaluated before the UDF loop, so a user UDF that already registers the name unix_timestamp would now be silently shadowed by the built-in.
1.3 Performance / Side-Effect Analysis
The function runs per row. It builds a DateTimeFormatter per call (DateTimeFunction.java:856), exactly as fromUnixTime (:800) and formatdatetime (:617) already do, so this is not a regression, but see Issue 4. No locks, no shared mutable state, no retries; the function is stateless and idempotent (except UNIX_TIMESTAMP() which is time dependent by definition).
1.4 Error Handling and Logging
Bad row data returns NULL instead of failing the job, and a bad pattern fails fast because it is a query-time error. Both are documented. No logging, which is appropriate here.
Issue 1: The time zone contract is only exercised under UTC, so the tests cannot tell "system default zone" from "UTC"
- Location:
SQLDateTimeFunctionsTest.java:332-447(TimeZone.setDefault(UTC)at :334) - Problem description: every typed-datetime and string case runs with the default zone forced to UTC. With
UTCas the default zone, an implementation that resolves against UTC (or againstZoneOffset.UTC) produces the same numbers as the one that usesZoneId.systemDefault(). The zone behavior is exactly the contract the issue discussion asked to pin down, and it is the part that would silently regress. - Potential risk: a later refactor that swaps
ZoneId.systemDefault()for UTC keeps this test green and shifts every result by the local offset for users outside UTC; this also breaks the "inverse ofFROM_UNIXTIME" promise. - Best improvement: add a case under a non-UTC default zone (for example
Asia/Shanghai, where2023-01-01 00:00:00must give1672502400) and a round trip assertionFROM_UNIXTIME(UNIX_TIMESTAMP(s), 'yyyy-MM-dd HH:mm:ss') = sthat holds in any zone. Splitting the single 11-scenario method into a few focused@Testmethods would also make a failure point at the broken form. - Severity: Medium
- Raised by another reviewer: No (related to the zone question @SEZ9 raised on #12699)
Issue 2: Impossible calendar dates are silently rolled back instead of returning NULL
- Location:
DateTimeFunction.java:856-863 - Problem description:
DateTimeFormatter.ofPattern(...)uses the SMART resolver, which clamps a day-of-month that is too large for the month. I checked this with a standalone snippet on JDK 11 using the sameparseBest(..., LocalDateTime::from, LocalDate::from)call:"2023-02-30 00:00:00"and"2023-02-29 00:00:00"both parse to2023-02-28T00:00, while"2023-13-01 00:00:00"and"2023-1-1 00:00:00"throw (and therefore return NULL). So the documented rule "unparseable string input returns NULL" holds for malformed text but not for an impossible date, which yields a plausible-looking but wrong epoch value. - Potential risk: silent data skew for dirty date columns, which is where users reach for this function in the first place.
- Best improvement: Option A (cheapest): keep the behavior, say so in the docs ("an out-of-range day-of-month is adjusted to the last valid day of that month"), and add a test that pins it. Option B: reject such input, for example by formatting the parsed value back and comparing with the input for fixed-width patterns, or by using
ResolverStyle.STRICT(note that STRICT needsuuuuinstead ofyyyy, so the default pattern and most user patterns would have to be rewritten, which is why I lean to Option A). The other date functions in this class use the same default resolver, so Option A is consistent. - Severity: Medium (non-blocking)
- Raised by another reviewer: No
Issue 3: The E2E only asserts NOT_NULL, so it cannot catch a wrong value
- Location:
func_unix_timestamp.conf(the threeAssertrules),TestSQLIT.java - Problem description: the results depend on the container time zone, so the author sensibly avoided exact numbers, but
NOT_NULLwould also pass for a function that returns any non-null long. - Best improvement: make the check zone independent with a round trip, for example select
from_unixtime(unix_timestamp(c2), 'yyyy-MM-dd HH:mm:ss') as rtand assert it equals the original string2023-01-01 00:00:00(both functions use the same default zone, so it holds anywhere). - Severity: Low
- Raised by another reviewer: No
Issue 4: Formatter is rebuilt for every row
- Location:
DateTimeFunction.java:856 - Problem description:
DateTimeFormatter.ofPatternparses the pattern on each call. It matchesfromUnixTime, so I would not block on it, but this is a per-row path in a connector pipeline that can see very large row counts. - Best improvement: use a
static finalformatter for the default pattern and, if you want, a small bounded cache keyed by pattern string for custom patterns. - Severity: Low
- Raised by another reviewer: No
Issue 5: A user UDF named unix_timestamp is now shadowed
- Location:
ZetaSQLFunction.java:626vs the UDF loop at :686 - Problem description: built-in cases are matched before the UDF loop, so any existing
ZetaUDFthat returnsfunctionName() == "UNIX_TIMESTAMP"stops being called after this change. It is a one-line risk shared by every new built-in, but worth a sentence in the docs or release note. - Severity: Low
- Raised by another reviewer: No
2. Code Quality Assessment
2.1 Coding Standards
Code is clear and the new public method has a Javadoc that states the zone and NULL contract, which is what I look for. The two inline comments around the NULL pattern are a little awkwardly wrapped but fine.
2.2 Test Coverage and Test Stability
Coverage of the forms is good (no-arg, default / custom / date-only patterns, null, unparseable, null pattern, numeric, three typed inputs), plus an E2E in TestSQLIT. It extends the existing test class instead of adding a new one, which is the right call.
Stability rating: Risk present. Evidence: SQLDateTimeFunctionsTest.java:334 / :447 mutates the JVM-wide default time zone (restored in finally, and the same pattern already exists at :241/:260, so I would not block on it, but it is unsafe if the module ever runs test methods in parallel), and the no-arg case (:340-352) uses a 60-second window, which is deterministic enough for CI. See Issue 1 for the zone coverage gap.
2.3 Documentation Updates
docs/en/transforms/sql-functions.md and docs/zh/transforms/sql-functions.md both gain a UNIX_TIMESTAMP section right after FROM_UNIXTIME, with matching content (signature, zone rule, NULL rules, examples). Please also mention the date clamping behavior if you choose Option A in Issue 2.
3. Architectural Soundness
- 3.1 Precise fix: a new built-in that follows the existing registration pattern.
- 3.2 Maintainability: the method is self-contained and well documented.
- 3.3 Extensibility: nothing here blocks adding a zone argument later.
- 3.4 Historical compatibility: see 1.2.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Zone contract only tested under UTC; add non-UTC and FROM_UNIXTIME round trip | SQLDateTimeFunctionsTest.java:332-447 |
Medium |
| 2 | Impossible dates (for example 2023-02-30) are clamped to a valid day instead of NULL | DateTimeFunction.java:856-863 |
Medium (non-blocking) |
| 3 | E2E asserts NOT_NULL only | func_unix_timestamp.conf |
Low |
| 4 | Formatter created per row | DateTimeFunction.java:856 |
Low |
| 5 | Built-in shadows a same-named user UDF | ZetaSQLFunction.java:626 |
Low |
CI and merge state (head d26d794d80a1)
Build is still in progress in the fork run (chovy-3012/seatunnel run 37947398578), so I cannot give a CI verdict yet. The branch is 25 commits behind dev with no conflicts. Note that the ElasticsearchIT slice tests are currently red on the dev head itself, so if that job shows up red here it is not caused by this PR.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers: none on the source side. Please wait for the in-progress
Buildto finish green (or only show the known dev-wide failures) and for a committer review. - Recommended, non-blocking: Issue 1 and Issue 2 (medium), then Issues 3-5.
Overall: a clean, well documented addition with the zone and NULL semantics spelled out. A non-UTC test and a decision on date clamping would make it solid. Thanks again!
|
Thanks for the thorough review! All items addressed: Issue 1 (timezone contract): Added a non-UTC test case under Issue 2 (impossible dates, Option A): Kept the SMART resolver clamping behavior. Documented in Javadoc and EN/ZH docs. Added a test case pinning the clamped value ( Issue 3 (E2E NOT_NULL): Added Issue 4 (per-row formatter): Added a Issue 5 (UDF shadowing): Added a note in both EN/ZH docs that a same-named UDF is shadowed by the built-in. |
b971057 to
7da0e1d
Compare
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks a lot for the quick turnaround, and for addressing every point from my previous round. I re-read the full diff of the current head 7da0e1dfff91 and re-traced the function through the Zeta SQL path. Status of my earlier items: Issue 1 (zone contract) is resolved by the Asia/Shanghai case at SQLDateTimeFunctionsTest.java:450; Issue 2 (date clamping) is resolved with Option A (documented in EN/ZH docs and Javadoc, pinned by case 12); Issue 3 (E2E NOT_NULL only) is resolved by the exact-value rt2 round trip in func_unix_timestamp.conf; Issue 5 (UDF shadowing) is resolved by the doc note. Issue 4 (formatter per row) was addressed, but the way it was done introduces one new, smaller concern, see Issue 1 below. No other reviewer has commented on this PR yet.
What Problem Does This PR Solve?
- User pain point: Hive / Spark SQL jobs using
UNIX_TIMESTAMPcannot move to the Zeta SQL transform (#12699). - Fix approach: new built-in
UNIX_TIMESTAMP(no-arg, typed datetime, string + optional pattern), returningLONG, parse failures give NULL, plus a shared formatter cache also used byFROM_UNIXTIME. - One-sentence summary: a pure-addition inverse of
FROM_UNIXTIMEwith explicit zone and NULL semantics.
1. Code Change Review
1.1 Core Logic Analysis
New since my last review: FORMATTER_CACHE + getFormatter (DateTimeFunction.java:51-55), used by fromUnixTime (:808) and unixTimestamp (:867); a non-UTC unit case and a clamping case; E2E rt2 assertion; doc notes.
Sql transform row -> ZetaSQLFunction.executeFunctionExpr("UNIX_TIMESTAMP") -> DateTimeFunction.unixTimestamp(args)
string path: pattern = args[1] (per-row evaluated expression) -> getFormatter(pattern)
-> FORMATTER_CACHE (static ConcurrentHashMap, never evicted) -> parseBest
Key findings:
- The normal SQL path reaches all new code; zone handling (
ZoneId.systemDefault()for local values, own offset forOffsetDateTime) and the NULL rules match the docs. The E2E round trip holds in any container zone because both functions use the same default zone. - The pre-existing
FROM_UNIXTIMEbehavior is unchanged: same formatter, invalid pattern still throws (computeIfAbsentdoes not store a failed mapping), and the existingFROM_UNIXTIMEtests/E2E still cover it.
1.2 Compatibility Impact
Fully compatible: pure addition, no option/default/serialization change. No upgrade action needed.
1.3 Performance / Side-Effect Analysis
Issue 1: The formatter cache is unbounded and keyed by row data
- Location:
DateTimeFunction.java:51-55 - Problem description: the
patternargument ofUNIX_TIMESTAMP(s, pattern)andFROM_UNIXTIME(n, pattern)is an arbitrary SQL expression evaluated per row, so it can be a column. The cache is astaticmap that is never evicted, so each distinct pattern string ever seen is retained for the lifetime of the JVM (in Zeta, the worker, across jobs). Before this PRfromUnixTimekept nothing, so this adds a new growth path to an existing function. - Potential risk: for a long-running streaming job with a dirty or high-cardinality pattern column, the map grows without bound; this is the classic slow heap leak. For constant literal patterns (the normal case) there is no problem, which is why I rate it Medium and not a blocker.
- Best improvement: Option A (simplest): only insert while
FORMATTER_CACHE.size()is below a small cap (for example 256) and otherwise build an uncached formatter. Option B: drop the cache entirely (what the code did before;ofPatternis cheap compared with the parse). Either is a few lines. - Severity: Medium (non-blocking)
- Raised by another reviewer: No
1.4 Error Handling and Logging
Bad row data returns NULL, a bad pattern fails fast; both documented. No logging, appropriate.
2. Code Quality Assessment
2.1 Coding Standards
Clean and consistent with surrounding code; Javadoc states the zone, NULL and clamping contract.
Issue 2: One 150-line test method with 12 scenarios
- Location:
SQLDateTimeFunctionsTest.java:332-482 - Problem description: a failure in an early scenario hides all later ones, and the zone switching in the middle (
:450, reset at :468) makes the order matter. A small unit-levelFROM_UNIXTIME(UNIX_TIMESTAMP(s))round trip under a non-UTC zone would also pin the inverse promise in the unit tests, not only the E2E. - Best improvement: split into a few focused
@Testmethods (no-arg, string forms, typed inputs, zone, clamping); non-blocking. - Severity: Low
- Raised by another reviewer: No
2.2 Test Coverage and Test Stability
Coverage is good: no-arg, default / custom / date-only patterns, NULL value, NULL pattern, unparseable, numeric, three typed inputs, non-UTC zone, clamping, plus the E2E in TestSQLIT. Stability rating: Risk present (low): the test mutates the JVM-wide default zone but restores it in finally (same pattern already exists elsewhere in this class), and the no-arg check uses a 60s window. Not a blocker.
2.3 Documentation Updates
EN and ZH docs both updated with matching content, including the clamping and UDF-shadowing notes.
3. Architectural Soundness
Follows the existing registration pattern; self-contained; nothing blocks adding a zone argument later. Historical compatibility: see 1.2.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Static formatter cache is unbounded and keyed by per-row pattern values | DateTimeFunction.java:51-55 |
Medium (non-blocking) |
| 2 | Single large test method; no unit-level round trip | SQLDateTimeFunctionsTest.java:332-482 |
Low |
CI and merge state (head 7da0e1dfff91)
Fork run chovy-3012/seatunnel 38112404403 is completed with failure, but the relevant lanes are green: unit-test (JDK 8/11, ubuntu and windows) and transform-v2-it-part-1/2 (JDK 8/11) all passed, so the new unit and E2E cases pass. The red lanes are engine-v2-it, engine-k8s-it (the failure is in the install k8s step, a download error) and elasticsearch-connector-it, none of which exercise the SQL transform; this PR only touches seatunnel-transforms-v2, docs and one transform E2E, so this is my inference that they are unrelated (the Elasticsearch one is also red on dev, as noted last time). The branch is 36 commits behind dev with no conflicts; please sync with the latest dev and rerun only the failed jobs. If they still fail after that, paste the failing check link here and I will help narrow it down.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers (non-CI): none.
- Recommended, non-blocking: Issue 1 (bound or drop the cache; small change, I would do it before merging), Issue 2 (low).
Overall: all earlier feedback has been addressed well and the semantics are clearly specified and tested. Once the unrelated CI lanes are green after a sync and a committer approves, this is good to go. Thanks again for the polish!
|
Thanks for the thorough second round. Both items are addressed in Issue 1 (cache cap): Issue 2 (test split): All 22 unit tests pass; spotless clean. |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks again for the quick and careful follow-up. I re-read the full diff of the current head 3df0352b9dfc (the delta since my last review at 7da0e1df is two files: DateTimeFunction.java and SQLDateTimeFunctionsTest.java) and re-traced the function through the Zeta SQL path. Both items from my last round are resolved, and I found no new issue. No other reviewer has commented on this PR.
What Problem Does This PR Solve?
- User pain point: Hive / Spark SQL jobs using
UNIX_TIMESTAMPcannot move to the Zeta SQL transform (#12699). - Fix approach: a new built-in
UNIX_TIMESTAMP(no-arg, typed datetime, string with optional pattern) returningLONG; unparseable strings give NULL; a small shared formatter cache is also used byFROM_UNIXTIME. - One-sentence summary: a pure-addition inverse of
FROM_UNIXTIMEwith explicit zone, NULL and date-clamping semantics.
1. Code Change Review
1.1 Core Logic Analysis
New since my last review:
DateTimeFunction.java:51-66: the formatter cache is now bounded.
// before (7da0e1df)
return FORMATTER_CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern);
// after (3df0352b)
DateTimeFormatter cached = FORMATTER_CACHE.get(pattern);
if (cached != null) return cached;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
if (FORMATTER_CACHE.size() < FORMATTER_CACHE_MAX_SIZE) { FORMATTER_CACHE.putIfAbsent(pattern, formatter); }
return formatter;SQLDateTimeFunctionsTest.java: the single 12-scenario method is split into focused@Testmethods (no-arg, string patterns, null/invalid, typed inputs, non-UTC zone, clamping), plustestFromUnixTimeUnixTimestampRoundTripunderAsia/Shanghai.
Sql transform row -> ZetaSQLFunction.executeFunctionExpr("UNIX_TIMESTAMP") -> DateTimeFunction.unixTimestamp(args)
string path: pattern = per-row expression -> getFormatter(pattern)
-> FORMATTER_CACHE hit | miss: ofPattern (invalid pattern throws before any insert) -> insert only if size < 1024
-> parseBest(LocalDateTime, LocalDate) -> epoch seconds (JVM default zone) | NULL on DateTimeException
Key findings:
- The normal SQL path reaches all new code. Zone handling (
ZoneId.systemDefault()for local values, own offset forOffsetDateTime) and NULL rules match the docs. - The cap is a soft cap: under concurrency the
size()check andputIfAbsentare not atomic, so the map can exceed 1024 by at most a few entries (bounded by the number of concurrent threads). That is harmless and keeps the hot path lock-free. - Behavior for
FROM_UNIXTIMEis unchanged: same formatter semantics, and an invalid pattern still throws becauseofPatternruns before any insert (nothing bad is cached). - Test split does not weaken anything: every scenario from the old method is still asserted with the same expected values; each test restores the default time zone in
finally.
1.2 Compatibility Impact
Fully compatible: pure addition, no option, default or serialization change, no upgrade action needed.
1.3 Performance / Side-Effect Analysis
Per-row cost is a map lookup for constant patterns. The cache is capped at 1024 entries (small retained heap), so a dirty or high-cardinality pattern column can no longer grow it without bound; beyond the cap it behaves like the pre-PR code (build a formatter per row). No locks, no shared mutable state beyond the concurrent map.
1.4 Error Handling and Logging
Bad row data returns NULL, a bad pattern fails fast; both documented. No logging, appropriate. No open issues.
2. Code Quality Assessment
2.1 Coding Standards
Clean and consistent with the surrounding class; the new constant and cache have clear intent. The contract (zone, NULL, clamping, UDF shadowing) is documented in Javadoc and docs.
2.2 Test Coverage and Test Stability
Coverage is good: no-arg, default / custom / date-only patterns, NULL value, NULL pattern, unparseable, numeric, three typed inputs, non-UTC zone, clamping, unit-level round trip, plus the E2E in TestSQLIT (func_unix_timestamp.conf). Each case can fail on a regression (for example swapping ZoneId.systemDefault() for UTC breaks the Shanghai and round-trip cases). Stability rating: Risk present (low): tests mutate the JVM-wide default zone but restore it in finally, and the no-arg check uses a 60s window. Not a blocker. (Optional nit: there is no direct test of the cache cap itself; I would not require one.)
2.3 Documentation Updates
EN and ZH sql-functions.md both updated with matching content.
3. Architectural Soundness
- 3.1 Elegance: Precise fix, following the existing registration pattern.
- 3.2 Maintainability: self-contained and well documented.
- 3.3 Extensibility: nothing blocks adding a zone argument later.
- 3.4 Historical-Version Compatibility: see 1.2; no impact on existing jobs.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| - | No open issues | - | - |
CI and merge state (head 3df0352b9dfc)
The fork Build run for this head (chovy-3012/seatunnel run 38185671979) is still queued, so I cannot give a CI verdict for this head yet; the apache-side Build check is in progress as a pointer to it. For reference, on the previous head the SQL-relevant lanes (unit-test, transform-v2-it-part-1/2) were green and the red lanes (engine-v2-it, engine-k8s-it, elasticsearch-connector-it) are outside this PR's diff. The branch has no conflicts but is 38 commits behind dev; merge state is BLOCKED only because a committer review is required (reviewDecision: REVIEW_REQUIRED).
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers (non-CI): none.
- Recommended fixes (non-blocking): none outstanding. Please let the fork
Buildfinish; if only the known unrelated lanes fail, rerun just those jobs.
Overall: all earlier feedback has been addressed cleanly, the cache is now safe for per-row patterns, and the semantics are clearly specified and tested. No better alternative design is needed. Once CI is green and a committer approves, this is good to go. Thanks for the polish!
SEZ9
left a comment
There was a problem hiding this comment.
Thanks for working on this. I reviewed the latest head 3df0352b9dfc.
What this PR fixes
- User pain: The Zeta SQL transform has
FROM_UNIXTIME(epoch -> formatted string) but no inverse, so users needing epoch seconds for a downstream sink, or MySQL/HiveUNIX_TIMESTAMPdialect parity, had to compute it outside the transform or ship aZetaUDF(#12699). - Fix approach: Adds
DateTimeFunction.unixTimestamp(List<Object>)(DateTimeFunction.java:845) wired viacase UNIX_TIMESTAMP: return DateTimeFunction.unixTimestamp(args);(ZetaSQLFunction.java:626-627) and typed asBasicType.LONG_TYPEinZetaSQLType.getFunctionType(ZetaSQLType.java:388); no-arg ->Instant.now(),OffsetDateTime-> own offset,LocalDateTime/LocalDate/strings (defaultyyyy-MM-dd HH:mm:ss,parseBest(str, LocalDateTime::from, LocalDate::from)) ->ZoneId.systemDefault(), parse failures swallowed to NULL (catch (DateTimeException e) { return null; }, lines 886-888). Also introduces a staticFORMATTER_CACHE(lines 51-66) that the pre-existingfromUnixTimeis now routed through (line 819). Covered by unit tests pinned to UTC / Asia/Shanghai, a NOT_NULL-only e2e conf, and EN/ZH docs. - One-line summary: Dispatch, type resolution and the happy paths are correct and the addition is self-contained, but the function is not a full inverse of
FROM_UNIXTIME(ts, fmt, tz)(no time-zone argument, string offsets discarded byparseBest, result tied to the worker JVM zone),getFormatter(pattern)sits outside thetryso a bad row-supplied pattern aborts the job with the cell echoed viasqlExpressionError, the never-evicting static cache can be permanently filled by one job, and the UDF shadowing is mentioned in the function docs but not recorded inincompatible-changes.md(the PR checklist marks it N/A). All fixable before merge; none of it blocks the design.
Runtime chain I rechecked
ZetaSQLEngine.project() -> zetaSQLFunction.computeForValue(expression, inputFields) ZetaSQLEngine.java:339 (any exception -> TransformCommonError.sqlExpressionError(expression.toString(), e) ZetaSQLEngine.java:342)
ZetaSQLFunction.computeForValue() expression instanceof Function -> args evaluated recursively (so args.get(1) may be a per-row column value) -> executeFunctionExpr(functionName, functionArgs, expression)
ZetaSQLFunction.executeFunctionExpr() -> zetaSQLType.getExpressionType(expression) -> ZetaSQLType.getFunctionType(Function)
case ZetaSQLFunction.UNIX_TIMESTAMP: return BasicType.LONG_TYPE ZetaSQLType.java:388 [CHANGED] (matched before the udfList loop in default: at ZetaSQLType.java:527-529)
switch (functionName.toUpperCase()) ... case UNIX_TIMESTAMP: return DateTimeFunction.unixTimestamp(args) ZetaSQLFunction.java:626-627 [CHANGED] (matched before the udfList loop in default: at ZetaSQLFunction.java:686-694 -> shadows a same-named ZetaUDF)
DateTimeFunction.unixTimestamp(List<Object>) DateTimeFunction.java:845
args.isEmpty() -> Instant.now().getEpochSecond() :847-848
OffsetDateTime -> toEpochSecond() :855-856
LocalDateTime / LocalDate -> atZone/atStartOfDay(ZoneId.systemDefault()).toEpochSecond() :858-863
string path: str = value.toString() :865; pattern = args[1] (NULL -> return null) or "yyyy-MM-dd HH:mm:ss" :867-877
getFormatter(pattern) :878 (OUTSIDE try) -> DateTimeFormatter.ofPattern(pattern) :61 -> IllegalArgumentException escapes to ZetaSQLEngine.java:342
try { formatter.parseBest(str, LocalDateTime::from, LocalDate::from) -> ZoneId.systemDefault() -> toEpochSecond } catch (DateTimeException) { return null } :879-889
DateTimeFunction.getFormatter() static FORMATTER_CACHE (ConcurrentHashMap, cap 1024, no eviction) DateTimeFunction.java:51-66 [CHANGED]
also now used by DateTimeFunction.fromUnixTime() -> getFormatter(format) DateTimeFunction.java:819 [CHANGED]
Findings
Issue 1: Invalid pattern values coming from a row column escape the NULL-on-bad-input contract: getFormatter(pattern) runs outside the try and throws IllegalArgumentException, which the catch (DateTimeException e) does not cover, so one bad cell aborts the job and echoes the cell value into the failure message.
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:878 - Why it matters: - Root cause: at DateTimeFunction.java:878
DateTimeFormatter formatter = getFormatter(pattern);is evaluated before thetryblock, andgetFormattercallsDateTimeFormatter.ofPattern(pattern)(line 61), which throwsIllegalArgumentException(e.g. "Unknown pattern letter: q", "Too many pattern letters"). The handler at line 886 only catchesDateTimeException, which is not a superclass ofIllegalArgumentException. - The Javadoc (lines 841-843) justifies this as "a query-time error rather than row data", but that assumption does not hold:
args.get(1)is produced byZetaSQLFunction#computeForValue, so the pattern can be any expression, including a STRING column.UNIX_TIMESTAMP(c2, c_pattern)is therefore evaluated per row with whatever the row contains. - Impact: the first row with a malformed pattern fails the whole task.
ZetaSQLEngine.project()wraps the exception inTransformCommonError.sqlExpressionError(expression.toString(), e)(ZetaSQLEngine.java:341-342), and theIllegalArgumentExceptionmessage embeds the raw pattern string, so the offending cell value lands in the job failure message and logs. This contradicts the documented contract (docs/en:1120 "Unparseable string input returns NULL rather than raising an error") for the only other string argument the function takes. - Suggested fix: move the
getFormatter(pattern)call inside thetryand also catchIllegalArgumentException(returning NULL), or validate literal patterns once at plan time and fail fast with aTransformExceptionthat names the pattern argument rather than the row. Add a unit case with a bad pattern (literal and column-sourced) toSQLDateTimeFunctionsTestand state the behaviour in the EN/ZH docs. - Evidence:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:61 DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:886 } catch (DateTimeException e) {;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:841 * consistent with the other date functions in this class. An invalid pattern string, being a - Suggested fix:
getFormatter(pattern)is outside thetry, andDateTimeFormatter.ofPatternthrowsIllegalArgumentException, which thecatch (DateTimeException e)below does not cover. The Javadoc treats the pattern as query-time only, butargs.get(1)is computed from any expression (ZetaSQLFunction#computeForValue), soUNIX_TIMESTAMP(c2, c_pattern)fails the whole task on the first malformed pattern cell, and the exception message (which embeds the raw pattern value) ends up in the job failure/log viasqlExpressionError. Could we move the formatter construction inside thetryand also catchIllegalArgumentException(returning NULL, matching the documented contract), or alternatively validate literal patterns once at plan time? Either way the EN/ZH docs should say what happens on an invalid pattern. - Severity: Medium
Issue 2: The EN/ZH function docs describe only the NULL-on-unparseable path and omit three user-visible behaviours implemented in this PR: an invalid pattern raises an error, a pattern without a full date (or a TIME column) yields NULL, and there is no timeZone argument so the 3-arg FROM_UNIXTIME form cannot be round-tripped.
- Location:
docs/en/transforms/sql-functions.md:1120 - Why it matters: - Root cause: the Javadoc at DateTimeFunction.java:841-843 correctly states that an invalid pattern "propagates from DateTimeFormatter.ofPattern" (called at line 878, outside the
try), but the user docs at docs/en/transforms/sql-functions.md:1120 and docs/zh/transforms/sql-functions.md:1125 only say "Unparseable string input returns NULL rather than raising an error", which a reader will naturally extend to a bad pattern. - Because
parseBest(line 881) only acceptsLocalDateTime/LocalDate, a pattern such as'HH:mm:ss'or'yyyy-MM'makes every row return NULL (the parse succeeds but neither query can be satisfied, raisingDateTimeExceptioninto the swallow-to-NULL catch). The same happens for a TIME column, whoseLocalTime.toString()never matches the default pattern. Neither case is mentioned. - The docs call the function "The inverse of
FROM_UNIXTIME" (line 1114), yetFROM_UNIXTIMEdocuments an optionaltimeZonethird argument (line 1095) andUNIX_TIMESTAMPhas none; the code hard-wiresZoneId.systemDefault()forLocalDateTime,LocalDateand string inputs (lines 859, 862, 883, 885).UNIX_TIMESTAMP(FROM_UNIXTIME(x, fmt, 'UTC+6'))therefore only round-trips when the worker JVM zone is UTC+6; the sentence "resolved against the system's time zone" does not make this limitation explicit. - Suggested fix: add one sentence for each behaviour in both EN and ZH, and one example using
AT TIME ZONE(documented immediately below at line 1130) to show how to obtain an epoch for a non-default zone via theOffsetDateTimebranch. - Evidence:
docs/zh/transforms/sql-functions.md:1125dateTime与字符串输入按系统时区折算;TIMESTAMP WITH TIME ZONE 值使用其自身偏移。无法解析的字符串输入返回 NULL,而不会抛出错误。;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:841 * consistent with the other date functions in this class. An invalid pattern string, being a;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:878 DateTimeFormatter formatter = getFormatter(pattern); - Suggested fix: This paragraph covers the NULL-on-unparseable case well, but three behaviours the code actually has are missing and will surprise users reading only this page:
getFormatter(pattern)runs outside thetry(DateTimeFunction.java:878), so an invalid pattern raises -- the Javadoc says this, the user docs do not.parseBestonly acceptsLocalDateTime/LocalDate, so a pattern without a full date ('HH:mm:ss','yyyy-MM') or a TIME column yields NULL for every row.- There is no
timeZoneargument, soUNIX_TIMESTAMP(FROM_UNIXTIME(x, fmt, 'UTC+6'))only round-trips when the worker JVM zone is UTC+6.
Could you add a sentence for each (and the same indocs/zh/transforms/sql-functions.md:1125), plus oneAT TIME ZONEexample showing how to convert in a non-default zone? - Severity: Medium
Issue 3: Built-in UNIX_TIMESTAMP silently shadows any user ZetaUDF of the same name (and forces its output type to BIGINT), but incompatible-changes.md is not updated as was done for AES_ENCRYPT/AES_DECRYPT
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLFunction.java:626 - Why it matters: - Root cause:
executeFunctionExprswitches onfunctionName.toUpperCase()and only reachesudfListin thedefault:branch (ZetaSQLFunction.java:686-694);ZetaSQLType.getFunctionTypedoes the same (ZetaSQLType.java:527-529). Addingcase UNIX_TIMESTAMP:to both switches (ZetaSQLFunction.java:626-627, ZetaSQLType.java:388) means any job that registered aZetaUDFnamedUNIX_TIMESTAMP-- the obvious workaround while the built-in was missing (#12699) -- is bypassed after upgrade. - Impact: the result value may change (e.g. a UDF returning milliseconds, or honouring a zone argument) and the declared output type is now forced to
BasicType.LONG_TYPEregardless of what the UDF'sresultTypereturned, which can break the downstream sink schema. The function docs do note "If a user-defined function (UDF) with the same name exists, it is shadowed by this built-in" (docs/en:1120, docs/zh:1125), but that is not where operators look before upgrading;docs/en/introduction/concepts/incompatible-changes.mdhas no UNIX_TIMESTAMP entry, and the PR description marks that checklist item "N/A, pure addition, no incompatible change". - Precedent: the identical situation for AES_ENCRYPT/AES_DECRYPT (PR#12403) was recorded in
incompatible-changes.mdlines 56-72 with affected component, impact and migration guidance. - Suggested fix: add an equivalent EN + ZH section (behaviour change, impact on a same-named UDF including the forced BIGINT type, migration: rename the UDF or switch to the built-in).
- Evidence:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLFunction.java:627 return DateTimeFunction.unixTimestamp(args);;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/ZetaSQLType.java:388 case ZetaSQLFunction.UNIX_TIMESTAMP:;docs/en/transforms/sql-functions.md:1120 ... If a user-defined function (UDF) with the same name exists, it is shadowed by this built-in. - Suggested fix: This
caseis evaluated before thedefault:UDF lookup below, so any existingZetaUDFnamedUNIX_TIMESTAMP(the natural workaround while the built-in was missing) is silently shadowed on upgrade, andZetaSQLTypenow forces the column to BIGINT regardless of what that UDF declared. The function docs mention the shadowing, but we handled the identical situation for AES_ENCRYPT/AES_DECRYPT with a section indocs/en/introduction/concepts/incompatible-changes.md(lines 56-72). Please add the equivalent entry (EN + ZH) for UNIX_TIMESTAMP with migration guidance, rather than marking that checklist item N/A. - Severity: Medium
Issue 4: FORMATTER_CACHE is a static, JVM-wide map with no eviction: once 1024 distinct row-supplied patterns have been seen on a long-lived Zeta worker it is permanently full, and every later call (including the pre-existing FROM_UNIXTIME path, now routed through the same cache) rebuilds the formatter on every row for the rest of the JVM lifetime.
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:62 - Why it matters: - Root cause: DateTimeFunction.java:51-66 add a
static final ConcurrentHashMappopulated with whateverpatternstring reachesgetFormatter;if (FORMATTER_CACHE.size() < FORMATTER_CACHE_MAX_SIZE) putIfAbsent(...)(lines 62-63) only stops growth, nothing is ever removed. Thesize()check-then-act is also not atomic, so concurrent tasks can push the map slightly past the cap. - Impact: on Zeta the worker JVM is shared across jobs and the class is static, so a single job whose pattern argument is a data column (or a job that sees many distinct literal patterns over time) fills the 1024 slots with one-off strings. After that, every
getFormattermiss falls back toDateTimeFormatter.ofPatternper row, for every job on that worker, until restart.fromUnixTime(line 819) was changed to use the same cache, so a pre-existing function inherits this degraded mode. The strings also stay referenced for the JVM lifetime (bounded at 1024, so a small leak, but a permanent one). - Suggested fix: either cache only literal patterns (resolve the formatter once per
Functionexpression at plan time rather than per row), or use a bounded LRU -- a synchronizedLinkedHashMapwithremoveEldestEntry, or shaded GuavaCacheBuilder.newBuilder().maximumSize(1024)-- so the cache keeps serving hot patterns after the cap is reached. - Evidence:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:62 if (FORMATTER_CACHE.size() < FORMATTER_CACHE_MAX_SIZE) {;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:63 FORMATTER_CACHE.putIfAbsent(pattern, formatter);;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:819 DateTimeFormatter df = getFormatter(format); - Suggested fix: The cap stops growth but there is no eviction, and this map is static and JVM-wide. On a Zeta worker that runs many jobs, one job with a per-row pattern column fills the 1024 slots with one-off patterns and from then on every call -- including
fromUnixTime, which now also goes throughgetFormatterat line 819 -- rebuilds the formatter per row for the life of the JVM. Thesize()check is also not atomic under concurrent tasks. I'd either cache only literal patterns (resolve once perFunctionexpression rather than per row) or switch to a bounded LRU (LinkedHashMapwithremoveEldestEntry, or shaded GuavaCacheBuilder.maximumSize) so the cache stays useful after the cap is hit. - Severity: Medium
Issue 5: A zone offset present in the input string and pattern (e.g. 'yyyy-MM-dd HH:mm:ssXXX') is parsed and then silently discarded, because parseBest only queries LocalDateTime/LocalDate and the result is re-bound to ZoneId.systemDefault().
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:881 - Why it matters: - Root cause:
formatter.parseBest(str, LocalDateTime::from, LocalDate::from)at DateTimeFunction.java:881 never tries an offset-aware query. ForUNIX_TIMESTAMP('2023-01-01 00:00:00+08:00', 'yyyy-MM-dd HH:mm:ssXXX')the formatter parses the offset successfully,LocalDateTime::fromsucceeds (it ignores the resolved offset field), and line 883 then appliesZoneId.systemDefault()instead of +08:00. - Impact: the result is wrong by the difference between the string's offset and the worker JVM zone, with no error or NULL to signal it. It also makes the function internally inconsistent: the typed
OffsetDateTimebranch at line 855-856 honours the offset, so a TIMESTAMP_TZ column and its string rendering for the same instant produce different epochs. Patterns withXXX/xxx/Z/VVare common in ingested log and API data. - Suggested fix:
parseBest(str, ZonedDateTime::from, OffsetDateTime::from, LocalDateTime::from, LocalDate::from)(most specific first) and calltoEpochSecond()on the zoned/offset result; add a unit case underAsia/Shanghaiasserting that'2023-01-01 00:00:00+00:00'with'yyyy-MM-dd HH:mm:ssXXX'yields 1672531200 (not 1672502400). - Evidence:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:883 return ((LocalDateTime) parsed).atZone(ZoneId.systemDefault()).toEpochSecond();;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:880 TemporalAccessor parsed =;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:881 formatter.parseBest(str, LocalDateTime::from, LocalDate::from); - Suggested fix:
parseBesthere only triesLocalDateTime::from/LocalDate::from, so when the pattern carries an offset ('yyyy-MM-dd HH:mm:ssXXX'with'2023-01-01 00:00:00+08:00') the offset is parsed and then thrown away -- line 883 re-binds the local value toZoneId.systemDefault(), producing a silently wrong epoch on any worker whose zone is not +08:00. The typedOffsetDateTimebranch above does honour the offset, so string and TIMESTAMP_TZ inputs for the same instant disagree. SuggestparseBest(str, OffsetDateTime::from, LocalDateTime::from, LocalDate::from)withtoEpochSecond()for the offset-aware branch, plus a unit case underAsia/Shanghaiasserting the +08:00 string yields 1672502400. - Severity: Medium
Issue 6: Pattern handling is inconsistent across argument types: getFormatter() sits outside the try (a bad pattern from a column aborts the job), while for typed inputs the pattern -- even an explicit NULL -- is silently ignored.
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:871 - Why it matters: - Root cause: the typed branches at DateTimeFunction.java:855-863 return before the pattern argument is inspected, so
UNIX_TIMESTAMP(tsCol, NULL)returns an epoch whileUNIX_TIMESTAMP(strCol, NULL)returns NULL (lines 871-873), andUNIX_TIMESTAMP(tsCol, 'garbage')succeeds although the same pattern on a string column throws. Separately,getFormatter(pattern)at line 878 is outside thetry, andDateTimeFormatter.ofPatternthrowsIllegalArgumentException, which thecatch (DateTimeException e)at line 886 does not cover. - Impact: the semantics of the second argument depend on the runtime type of the first, which is surprising in a SQL function and makes a query behave differently when a source column changes from STRING to TIMESTAMP. The explicit-NULL rule the PR description and tests establish (
testUnixTimestampNullAndInvalid) only holds for string input. - Suggested fix: resolve and validate the pattern argument once, before the type dispatch (NULL -> NULL for all input types; invalid -> either NULL inside the
tryor a plan-time error), or document thatpatternis only consulted for string input. - Evidence:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:872 return null;;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:878 DateTimeFormatter formatter = getFormatter(pattern);;seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:886 } catch (DateTimeException e) { - Suggested fix: Two inconsistencies around the pattern argument: (a) this NULL check is only reached for string input --
UNIX_TIMESTAMP(tsCol, NULL)returns an epoch because the typed branches above return first, so NULL-pattern semantics depend on the first argument's type; (b)getFormatter(pattern)at line 878 is outside thetry, andofPatternthrowsIllegalArgumentException(not aDateTimeException), so a malformed pattern coming from a column fails the job rather than yielding NULL. I'd evaluate the pattern once before the type dispatch and either document thatpatternmust be a literal or move the formatter construction inside thetry. - Severity: Low
Issue 7: Any non-temporal, non-string argument (TIME column, BOOLEAN, DECIMAL, BYTES) falls through value.toString() and the default pattern, turning a schema/type mistake into a silent all-NULL column.
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:865 - Why it matters: - Root cause: after the three typed branches, line 865
String str = value.toString();accepts anything; aLocalTimebecomes"00:00:00", aBooleanbecomes"true", abyte[]becomes"[B@...", and each then fails the default pattern inside thecatch (DateTimeException e) { return null; }at line 886-888. - Impact: a user who points
UNIX_TIMESTAMPat a TIME column or a wrong field gets 100% NULL output with no error or log line, which is hard to diagnose downstream. The docs (docs/en:1120) explicitly state that numeric input returns NULL and the unit testtestUnixTimestampNullAndInvalidpins that for BIGINT, so the numeric case is intentional; TIME, BOOLEAN and BYTES are not covered by that statement and are not plausible row data that should be "unparseable". - Suggested fix: gate the parse path on
value instanceof String(andinstanceof Numberif numeric->NULL is to be kept) and throw aTransformExceptionnaming the unsupported type for everything else, so the NULL contract only applies to genuinely unparseable row data. - Evidence:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:888 return null; - Suggested fix:
value.toString()means a TIME column (LocalTime), a BOOLEAN or a BYTES field all silently become NULL for every row via the catch below -- a wrong column reference produces no error and no log. Numeric->NULL is documented and tested, so that one is intentional, but I'd gate this path onvalue instanceof String(plus an explicitinstanceof Numberbranch) and throw aTransformExceptionnaming the unsupported type for everything else, so the NULL contract only applies to genuinely unparseable row data. - Severity: Low
Issue 8: E2E asserts only NOT_NULL for the TIMESTAMP and custom-pattern paths, so a wrong epoch from those branches would still pass
- Location:
seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/resources/sql_transform/func_unix_timestamp.conf:47 - Why it matters: - The new
func_unix_timestamp.confquery (line 47) exercises three branches -- TIMESTAMP columnc1, default-pattern stringc2, custom-pattern stringc3-- but the Assert rules forts1,ts2,ts3areNOT_NULLonly (lines 57-76, e.g. line 60). Onlyrt2(round trip ofc2, line 81) checks a value, so theLocalDateTimebranch and the custom-pattern branch are never value-checked at the engine level; an off-by-zone or wrong-pattern result would still exit 0. - Since the container's zone is not fixed, absolute epoch values cannot be asserted, but zone-independent relations can: all three inputs denote 2023-01-01T00:00:00 in the same (default) zone, so
unix_timestamp(c1) - unix_timestamp(c2)andunix_timestamp(c3, 'yyyy/MM/dd HH:mm:ss') - unix_timestamp(c2)must both be 0, andfrom_unixtime(unix_timestamp(c3, 'yyyy/MM/dd HH:mm:ss'), 'yyyy-MM-dd HH:mm:ss')must equal"2023-01-01 00:00:00". - Suggested fix: add those derived columns with
equals_torules so the e2e actually pins the values of every branch it runs. - Evidence:
seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/resources/sql_transform/func_unix_timestamp.conf:60 {rule_type = NOT_NULL};seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/resources/sql_transform/func_unix_timestamp.conf:58 {rule_type = NOT_NULL};seatunnel-e2e/seatunnel-transforms-v2-e2e/seatunnel-transforms-v2-e2e-part-2/src/test/resources/sql_transform/func_unix_timestamp.conf:47 query = "select unix_timestamp(c1) as ts1, unix_timestamp(c2) as ts2, unix_timestamp(c3, 'yyyy/MM/dd HH:mm:ss') as ts3, from_unixtime(unix_timestamp(c2), 'yyyy-MM-dd HH:mm:ss') as rt2 from dual" - Suggested fix:
ts1/ts2/ts3are only asserted NOT_NULL, so the TIMESTAMP-column branch and the custom-pattern branch are never value-checked end to end. Without pinning the container zone you can still make this deterministic: addunix_timestamp(c1) - unix_timestamp(c2) as diff(must be 0, both are 2023-01-01T00:00:00 in the same zone) andfrom_unixtime(unix_timestamp(c3, 'yyyy/MM/dd HH:mm:ss'), 'yyyy-MM-dd HH:mm:ss') as rt3withequals_to = "2023-01-01 00:00:00". - Severity: Low
Review conclusion
Conclusion: final approval remains pending on the previous comments
2. Remaining follow-ups
- Issue 1: Invalid pattern values coming from a row column escape the NULL-on-bad-input contract:
getFormatter(pattern)runs outside the try and throwsIllegalArgumentException, which thecatch (DateTimeException e)does not cover, so one bad cell aborts the job and echoes the cell value into the failure message. - Issue 2: The EN/ZH function docs describe only the NULL-on-unparseable path and omit three user-visible behaviours implemented in this PR: an invalid pattern raises an error, a pattern without a full date (or a TIME column) yields NULL, and there is no timeZone argument so the 3-arg FROM_UNIXTIME form cannot be round-tripped.
- Issue 3: Built-in UNIX_TIMESTAMP silently shadows any user ZetaUDF of the same name (and forces its output type to BIGINT), but incompatible-changes.md is not updated as was done for AES_ENCRYPT/AES_DECRYPT
- Issue 4:
FORMATTER_CACHEis a static, JVM-wide map with no eviction: once 1024 distinct row-supplied patterns have been seen on a long-lived Zeta worker it is permanently full, and every later call (including the pre-existingFROM_UNIXTIMEpath, now routed through the same cache) rebuilds the formatter on every row for the rest of the JVM lifetime. - Issue 5: A zone offset present in the input string and pattern (e.g. 'yyyy-MM-dd HH:mm:ssXXX') is parsed and then silently discarded, because parseBest only queries LocalDateTime/LocalDate and the result is re-bound to ZoneId.systemDefault().
- Issue 6: Pattern handling is inconsistent across argument types: getFormatter() sits outside the try (a bad pattern from a column aborts the job), while for typed inputs the pattern -- even an explicit NULL -- is silently ignored.
- Issue 7: Any non-temporal, non-string argument (TIME column, BOOLEAN, DECIMAL, BYTES) falls through value.toString() and the default pattern, turning a schema/type mistake into a silent all-NULL column.
- Issue 8: E2E asserts only NOT_NULL for the TIMESTAMP and custom-pattern paths, so a wrong epoch from those branches would still pass
Thanks for the updates so far. Happy to discuss the remaining points.
|
Thanks @chovy-3012. A quick CI update, because my last review described the fork That run has now finished with Separately, @SEZ9 posted a full review on the same head after mine, with eight follow-up items (for example the |
3df0352 to
2f0c133
Compare
|
Thanks for the thorough review. All 8 items are addressed in Issue 1: Issue 2: EN/ZH function docs expanded to cover offset-aware string parsing, NULL/invalid pattern → NULL for all input types, pattern consulted only for string input, no Issue 3: Added "Zeta SQL Transform: built-in UNIX_TIMESTAMP" entry to EN/ZH Issue 4: Issue 5: Issue 6: Pattern resolution (NULL check + Issue 7: Explicit Issue 8: E2E |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the thorough follow-up, and sorry that I missed these items earlier. My previous round approved the shape of the change, but @SEZ9's review on 3df0352b9dfc was right about several things I did not catch: the getFormatter(pattern) call outside the try, string inputs with a zone offset, the NULL-pattern behaviour, and the missing incompatible-changes.md entry. I re-read the full diff of the current head 2f0c133e8037 (5 commits, 0 behind dev) and re-traced the function through the Zeta SQL path. All eight of SEZ9's items are resolved in code, and I found no new blocking issue.
What Problem Does This PR Solve?
- User pain point: Hive / Spark / MySQL jobs that use
UNIX_TIMESTAMPcannot move to the Zeta SQL transform; users had to rewrite them withPARSEDATETIMEplus epoch arithmetic or ship aZetaUDF(#12699). - Fix approach: register
UNIX_TIMESTAMP(no-arg, typed datetime, string with optional pattern), resolve the type asLONG, and share a boundedDateTimeFormattercache withFROM_UNIXTIME. - One-sentence summary: the inverse of the existing
FROM_UNIXTIME, added as a self-contained addition with documented semantics.
1. Code Change Review
1.1 Core logic and runtime path
ZetaSQLEngine.project() -> ZetaSQLFunction.computeForValue() -> executeFunctionExpr()
ZetaSQLType.getFunctionType: case UNIX_TIMESTAMP -> LONG_TYPE (ZetaSQLType.java:389)
switch: case UNIX_TIMESTAMP -> DateTimeFunction.unixTimestamp(args) (ZetaSQLFunction.java:647)
DateTimeFunction.unixTimestamp (DateTimeFunction.java:851)
no args -> Instant.now().getEpochSecond()
NULL value -> NULL; NULL pattern -> NULL for all input types
getFormatter(pattern) now inside try/catch(IllegalArgumentException) -> NULL (:872)
OffsetDateTime -> own offset; LocalDateTime/LocalDate -> ZoneId.systemDefault() (:886, :889)
Number -> NULL (documented); other non-String types -> TransformException (:899)
String -> parseBest(ZonedDateTime, OffsetDateTime, LocalDateTime, LocalDate); DateTimeException -> NULL
Before: invalid row-sourced patterns escaped as IllegalArgumentException and failed the job; string offsets were discarded. After: bad pattern gives NULL (consistent with the documented "unparseable -> NULL" contract), and an offset carried by the pattern is honoured. I verified the dispatch precedes the UDF loop, so the shadowing described in the docs is accurate.
1.2 Compatibility
Partially incompatible (documented, narrow). A job that registered a ZetaUDF named UNIX_TIMESTAMP will now get the built-in, and the output type is forced to BIGINT. This is now recorded in EN and ZH incompatible-changes.md with impact and migration guidance, following the AES_ENCRYPT precedent. No existing built-in changes behaviour: FROM_UNIXTIME only switches from a per-call ofPattern to the cached formatter with identical results and identical exception type for a bad pattern. No config option, SPI or serialization change.
1.3 Performance and side effects
FORMATTER_CACHE (DateTimeFunction.java:55-67) is capped at 1024 entries, so per-row pattern columns can no longer grow memory without bound. Once full, extra patterns get an uncached formatter (correct, just slower). There is no eviction, so a job with many distinct patterns could fill it for the lifetime of the worker JVM; this is only a performance degradation, never a correctness issue.
1.4 Error handling and logging
No swallowed exceptions beyond the intentional, documented NULL-on-unparseable behaviour. Unsupported non-temporal types raise a TransformException naming the function and type, so schema mistakes are not silent.
Issue 1 (SEZ9 item 4, still open by design)
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/DateTimeFunction.java:55-67 - Problem: the formatter cache never evicts, so one job with more than 1024 distinct patterns permanently disables caching for later jobs on the same worker.
- Potential risk: slower pattern resolution only; no wrong results, no memory growth.
- Best improvement: optional, e.g. a small LRU or a per-call fallback is fine, but the current comment explains the trade-off well.
- Severity: Low
- Raised by another reviewer: yes, @SEZ9 (I agree the author's explanation is acceptable).
2. Code Quality Assessment
2.1 Coding standards
Consistent with the surrounding class; the Javadoc on unixTimestamp states zone, NULL, clamping and UDF-shadowing semantics, and the cache constant carries a rationale comment.
2.2 Test coverage and stability
SQLDateTimeFunctionsTest now has focused cases for no-arg, string patterns, NULL/invalid pattern, typed inputs, non-UTC zone, SMART clamping, round trip with FROM_UNIXTIME, invalid pattern, offset-bearing strings, NULL pattern with typed input, unsupported type, and the AT TIME ZONE example. These would fail on realistic regressions (for example replacing ZoneId.systemDefault() with UTC, or moving getFormatter back outside the try). The E2E func_unix_timestamp.conf now also asserts exact values (rt3, diff1), not only NOT_NULL. No existing test was weakened. Stability rating: Risk present (low): tests change the JVM default zone but restore it in finally, and the no-arg check uses a time window.
2.3 Documentation
EN and ZH sql-functions.md and incompatible-changes.md are updated with matching content.
3. Architectural Soundness
The change follows the existing function-registration pattern, stays inside the transform module, and does not touch engine, core or API. A time-zone argument can be added later without breaking the current signature.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | Formatter cache has no eviction once full | DateTimeFunction.java:55-67 | Low |
CI and merge state (head 2f0c133e8037)
The fork Build run (chovy-3012/seatunnel run 39152422840) is red, so the apache-side Build is red. The failed jobs are unit-test (JDK 11 and 17 on ubuntu, and Windows), all-connectors-it-4 (11), and two cancelled mysql-cdc-connector-it jobs. I opened the logs: the unit-test failure is a single test, JdbcOptionRuleCompletenessTest.testSinkRuleDeclaresAllSinkOptions ("Connector 'Jdbc' has unknown option keys: [numeric_special_value_as_null]"), which comes from the interaction of two recent dev changes in the JDBC connector and does not touch this diff (the branch is 0 commits behind dev). all-connectors-it-4 fails in AzureCosmosDBSourceIT, also unrelated. The SQL-relevant lanes (transform-v2-it) passed. The branch has no conflicts; merge state is BLOCKED only because a committer review is required.
5. Merge Recommendation
Conclusion: Ready to merge
- Blockers (non-CI): none.
- Non-blocking: the cache-eviction note above.
- CI: red lanes are unrelated to this diff (a
dev-level JDBC option test and a Cosmos DB IT). Please re-run only the failed jobs oncedevis fixed; there is no need to change this PR.
Overall: every earlier finding has been addressed with code, docs and tests, and the semantics are now clearly specified. Thanks again for the patience and polish!
|
Hi @chovy-3012, one small thing on
The parse path is the sharper case, and it is new here.
} catch (DateTimeException e) {
// Unparseable input returns NULL rather than throwing
return null;
}and The suggested change is to construct with an explicit locale: DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
Your tests would not catch this: no pattern in Whichever of this PR and #12976 merges second will need a trivial rebase on that method. Happy either way, and happy to leave it entirely to you. |
|
Thanks @SEPURI-SAI-KRISHNA, good catch, and I agree with the analysis. I confirmed on the current head @chovy-3012, I would treat this as a small follow-up on this PR rather than something to leave to #12976:
The docs can stay as they are, apart from one line saying text patterns are interpreted in English. I will re-check once the commit is pushed (this review is by code reading only, nothing executed locally). Also, the apache-side |
2f0c133 to
e24b7a3
Compare
|
Thanks @SEPURI-SAI-KRISHNA for catching this, and @DanielLeens for the recommendation. Fixed in Added two regression tests under The direct |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the quick and precise follow-up on the locale issue, @chovy-3012, and thanks to @SEPURI-SAI-KRISHNA for raising it. I re-read the full diff of the current head e24b7a3f1a12 (6 commits ahead of dev, 2 behind, no conflicts) and re-traced the function through the Zeta SQL path. The six commits since my last review at 2f0c133e8037 reduce to one new commit (e24b7a3f1) touching getFormatter, two new unit tests, and EN/ZH docs. Everything raised earlier by @SEZ9 and in my previous round stays resolved. I found one small documentation blocker introduced by this last commit and a few low items.
What Problem Does This PR Solve?
- User pain point: Hive / Spark / MySQL jobs that use
UNIX_TIMESTAMPcannot move to the Zeta SQL transform; users had to rewrite them withPARSEDATETIMEplus epoch arithmetic or ship aZetaUDF(#12699). - Fix approach: register
UNIX_TIMESTAMP(no-arg, typed datetime, string with optional pattern), type it asLONG, and share a boundedDateTimeFormattercache withFROM_UNIXTIME. - One-sentence summary: the inverse of
FROM_UNIXTIME. Example:SELECT UNIX_TIMESTAMP('2023-01-01 00:00:00') FROM dualreturns the epoch seconds in the worker time zone.
1. Code Change Review
1.1 Core logic
New in this head (DateTimeFunction.java:65):
// before
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
// after
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);ZetaSQLEngine.project() -> ZetaSQLFunction.computeForValue() -> executeFunctionExpr()
UNIX_TIMESTAMP -> DateTimeFunction.unixTimestamp (:872, :907) -> getFormatter(pattern) [ENGLISH now]
FROM_UNIXTIME -> DateTimeFunction.fromUnixTime (:823) -> getFormatter(format) [ENGLISH now]
Key findings: the fix is in the right place (single choke point for both functions, and the cache key is now honest because the locale is fixed). Locale.ENGLISH matches DAYNAME / MONTHNAME in the same class. The previous items (pattern inside try, offset-bearing strings, NULL pattern, unsupported types, E2E exact values, incompatible-changes entry) are all still in place. The normal user path (any UNIX_TIMESTAMP / FROM_UNIXTIME call) reaches this change.
1.2 Compatibility
Partially incompatible (documented for UNIX_TIMESTAMP, not yet for FROM_UNIXTIME). The built-in shadowing of a same-named UDF is recorded in incompatible-changes.md. The new locale pinning also changes an existing function: FROM_UNIXTIME(ts, 'dd MMM yyyy') on a worker whose FORMAT locale is not English used to render localized text (for example Okt on de-DE) and will now render Oct. Numeric-only patterns are unaffected, so most jobs see no change, but it is a behaviour change of a released function and the current incompatible-changes.md entry only talks about UNIX_TIMESTAMP. See Issue 1.
1.3 Performance and side effects
No new cost. FORMATTER_CACHE stays capped at 1024 entries with no eviction (carried over, Low, see Issue 3).
1.4 Error handling and logging
Unchanged and consistent: bad pattern or unparseable text gives NULL, unsupported types raise TransformException.
Issue 1: FROM_UNIXTIME locale change is not recorded in incompatible-changes.md
- Location:
docs/en/introduction/concepts/incompatible-changes.mdanddocs/zh/introduction/concepts/incompatible-changes.md(theUNIX_TIMESTAMPentry); behaviour atDateTimeFunction.java:65and:823 - Problem: text pattern letters (
MMM,EEE,a, ...) inFROM_UNIXTIMEwere rendered in the worker JVM locale and are now always English. The project guide requires any incompatible change to be listed there with migration guidance. - Risk: a job on a non-English worker that relied on localized month or day names silently changes output after upgrade.
- Best improvement: add two sentences to the existing built-in
UNIX_TIMESTAMPentry (EN and ZH): what changed (text pattern letters inFROM_UNIXTIME/UNIX_TIMESTAMPare now English), impact (only non-English default FORMAT locale and text patterns), migration (none needed for numeric patterns; for localized output post-process the string). - Severity: Medium (blocking, documentation only)
- Raised by another reviewer: No
Issue 2: The new doc sentence is broader than the behaviour
- Location:
docs/en/transforms/sql-functions.md(new sentence underFROM_UNIXTIMEand at the end of theUNIX_TIMESTAMPparagraph),DateTimeFunction.java:640(FORMATDATETIME) andZetaDateTimeFormat.java:51(PARSEDATETIME) - Problem:
FORMATDATETIMEandPARSEDATETIMEstill build formatters with the default locale, so "interpreted in English, independent of the worker JVM locale" is only true for these two functions. @SEPURI-SAI-KRISHNA tracks the rest in #12976. - Risk: users may assume the whole date-time family is locale independent. Documentation only.
- Best improvement: keep the sentence but scope it explicitly to
FROM_UNIXTIMEandUNIX_TIMESTAMP. - Severity: Low
- Raised by another reviewer: Partially, @SEPURI-SAI-KRISHNA (#12976 covers the other call sites)
Issue 3: Formatter cache never evicts once full
- Location:
DateTimeFunction.java:55-67 - Problem: more than 1024 distinct patterns in one worker lifetime disables caching for later jobs. Performance only, never correctness.
- Best improvement: optional, a small LRU. The current rationale comment is acceptable.
- Severity: Low
- Raised by another reviewer: Yes, @SEZ9 (previously accepted)
2. Code Quality
2.1 Standards
Consistent with the class; the new test comments explain why they fail without the fix.
2.2 Tests and stability
testUnixTimestampTextPatternLocaleIndependent (parse 23 Oct 2026 with dd MMM yyyy under Locale.GERMANY, expected 1792684800, which I checked is Asia/Shanghai midnight) and testFromUnixTimeTextPatternLocaleIndependent (renders Oct under Locale.GERMANY) both fail if the Locale.ENGLISH argument is removed, so they have real failure power. Nothing existing was weakened. Stability: Risk present (low). They mutate the JVM-global FORMAT locale and default time zone and restore both in finally; this is safe only while the test class is not run in parallel with other tests in the same JVM. The no-arg test still uses a time window (carried over). A FROM_UNIXTIME pattern with EEE or a would also be worth one assertion, but is not required.
2.3 Docs
EN and ZH are updated consistently; see Issues 1 and 2.
3. Architecture
3.1 Precise fix for the locale problem, at the single shared construction point. 3.2 No engine, core or API changes. 3.3 The remaining default-locale call sites (FORMATDATETIME, PARSEDATETIME) are correctly left to #12976 to keep this PR focused; whichever merges second needs a trivial rebase. 3.4 A future time zone argument can be added without breaking the signature.
4. Issue Summary
| # | Issue | Location | Severity |
|---|---|---|---|
| 1 | FROM_UNIXTIME locale change missing from incompatible-changes (EN/ZH) |
incompatible-changes.md, DateTimeFunction.java:65 | Medium (blocking, docs) |
| 2 | Doc sentence broader than the behaviour | sql-functions.md | Low |
| 3 | Cache has no eviction once full | DateTimeFunction.java:55-67 | Low |
CI and merge state (head e24b7a3f1a12)
No usable CI result exists for this head. The fork Build run (chovy-3012/seatunnel run 40540261373) is cancelled, and the apache-side PR signal run (40540274841) is action_required, so nothing has actually executed against this commit. The previous head's red lanes were an unrelated JDBC option test and a Cosmos DB IT; they cannot be confirmed fixed on this head. Branch is 2 commits behind dev, diverged without conflicts; merge state is BLOCKED because a committer approval is required. There are no maintainer approvals or change requests on record, only comment reviews.
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers (non-CI): Issue 1 (documentation only, two short paragraphs).
- Non-blocking: Issues 2 and 3.
- CI: please re-trigger the fork
Buildfor this head (re-run the cancelled run) and share the result; I will check the failing lanes, if any, against the diff.
Overall this is very close. The code and tests for the locale fix are correct; only the compatibility note remains. Thank you for the patience and the polish.
|
Thanks for the follow-up in One remaining item before I approve: because Once that is in, I'm happy to approve. Thanks for sticking with this. |
|
Thanks @SEZ9 for following up. The current head is unchanged, so my existing non-CI Issue 1 remains open: add the EN/ZH incompatible-change note for locale-sensitive FROM_UNIXTIME output. The earlier UNIX_TIMESTAMP entry does not cover that distinct behavior. The optional wording/cache notes remain optional. CI recovery alone will not close that documentation request. Gate snapshot (2026-10-28T15:54:55+00:00), head The blocking jobs are Run / all-connectors-it-3 (11, ubuntu-latest) Observed log evidence: Please inspect or rerun only the named failed job where a rerun is appropriate. The logs establish the failing stage, but do not alone establish whether the current PR caused it. No matching upstream cure has been proved by this follow-up; a base sync alone is not a verified resolution, so no unrelated module/dependency patch is requested. My previous source conclusion remains unchanged, including its independent source/documentation requests. CI is not being passed by inference, and this follow-up is not an effective approval. Comparison recorded in this scan: base |
The inverse of FROM_UNIXTIME. Supported forms: - UNIX_TIMESTAMP(): current epoch seconds - UNIX_TIMESTAMP(dateTime): TIMESTAMP / TIMESTAMP_TZ / DATE column - UNIX_TIMESTAMP(string[, pattern]): string parsed with an optional pattern (default yyyy-MM-dd HH:mm:ss); unparseable input returns NULL.
…test The custom-pattern case paired a slash pattern (yyyy/MM/dd) with a dash-formatted value, which would parse to NULL and trip the NOT_NULL assertion. Use a dedicated slash-formatted input for the custom-pattern case.
…nction - Add non-UTC timezone test case (Asia/Shanghai) to verify systemDefault contract (Issue 1) - Keep SMART resolver clamping for impossible dates, document in Javadoc and EN/ZH docs, pin clamped value in test (Issue 2, Option A) - Add zone-independent round-trip assertion in E2E config (Issue 3) - Add ConcurrentHashMap-backed formatter cache shared by unixTimestamp and fromUnixTime (Issue 4) - Document UDF shadowing behavior in EN/ZH docs (Issue 5)
…_TIMESTAMP - Bound FORMATTER_CACHE to 1024 entries (static map was unbounded, keyed by per-row pattern) - Split testUnixTimestamp into 7 focused @test methods - Add unit-level FROM_UNIXTIME(UNIX_TIMESTAMP(s)) round-trip test under non-UTC zone
…_TIMESTAMP All 8 SEZ9 review items addressed in this commit: 1. Invalid pattern from a row column no longer aborts the job. getFormatter(pattern) moved before type dispatch and wrapped in try/catch(IllegalArgumentException) -> NULL, matching the documented NULL-on-bad-input contract. 2. EN/ZH function docs expanded to cover offset-aware string parsing, NULL/invalid pattern returns NULL for all input types, pattern only consulted for string input, no timeZone argument, and an AT TIME ZONE workaround example. 3. Added 'Zeta SQL Transform: built-in UNIX_TIMESTAMP' entry to EN/ZH incompatible-changes.md with behavior change / affected component / impact / migration guide, matching the AES_ENCRYPT/AES_DECRYPT precedent. 4. FORMATTER_CACHE design rationale documented inline (cap-only, no eviction by design: 1024 is far beyond real-world distinct patterns). 5. Offset-aware string parsing: parseBest chain extended with ZonedDateTime::from and OffsetDateTime::from before the local queries. 6. Pattern resolution moved before type dispatch so NULL/invalid pattern returns NULL for all input types, not only for string input. 7. Numeric input -> NULL (documented); other non-temporal/non-string types raise TransformException so a schema/type mistake is not silent. 8. E2E func_unix_timestamp.conf strengthened with diff1 (equals_to 0) and rt3 (equals_to '2023-01-01 00:00:00') exact-value assertions. Tests: 27/27 pass (22 existing + 4 round-3 + 1 AT TIME ZONE doc-example regression test). Spotless check passes.
…atterns DateTimeFormatter.ofPattern(pattern) captured the JVM default FORMAT locale, so text pattern letters (MMM, EEE, a, G, QQQ) failed on non-English workers: UNIX_TIMESTAMP returned NULL on the parse path and FROM_UNIXTIME rendered month/weekday names in the worker's language. Pin getFormatter to Locale.ENGLISH, consistent with DAYNAME/MONTHNAME which already uses DateFormatSymbols.getInstance(Locale.ENGLISH). Add two locale-independence tests that run under Locale.GERMANY and document that text patterns are interpreted in English regardless of the worker JVM locale.
…changes Add EN/ZH incompatible-changes entry for the FROM_UNIXTIME and UNIX_TIMESTAMP text-pattern locale change introduced by the getFormatter Locale.ENGLISH fix. The existing UNIX_TIMESTAMP entry covers UDF shadowing only; this entry documents the distinct behavior change where text pattern letters (MMM, EEE, etc.) now render and parse in English regardless of the worker JVM locale.
e24b7a3 to
af865b1
Compare
|
Added the |
There was a problem hiding this comment.
Thanks for adding the bilingual FROM_UNIXTIME locale migration entry. That closes the remaining documentation blocker from my review and the same request in @SEZ9's follow-up. The new-head Build is still in progress.
What Problem Does This PR Solve?
User pain point: Zeta SQL lacked a built-in conversion from supported dates/timestamps to epoch seconds, and text date patterns depended on the worker FORMAT locale.
Fix approach: Register UNIX_TIMESTAMP in value dispatch and BIGINT type resolution, preserve explicit offsets, and share an English-locale formatter factory with FROM_UNIXTIME.
One-sentence summary and example: An offset-bearing string uses its own offset. A local 2023-01-01 midnight uses the worker zone; under UTC+8 its epoch is 1672502400. English month patterns now parse/format consistently across worker locales.
1. Code Change Review
1.1 Core Logic Analysis
ZetaSQLEngine projects each row through computeForValue, which evaluates function arguments before executeFunctionExpr. The new switch arm calls unixTimestamp before UDF fallback, and ZetaSQLType declares LONG. Pattern null/invalid handling occurs before typed dispatch. OffsetDateTime uses its offset; LocalDateTime/LocalDate use the system zone. String parseBest tries zoned and offset-aware forms before local date/time forms. Numeric input returns null; unsupported non-temporal input raises TransformException.
Before:
// No UNIX_TIMESTAMP built-in; matching UDF may handle it.
DateTimeFormatter.ofPattern(format); // FROM_UNIXTIME captures default FORMAT localeAfter:
case UNIX_TIMESTAMP: return DateTimeFunction.unixTimestamp(args);
// Shared formatter construction pins Locale.ENGLISH.Key Findings
- Normal SQL rows reach both the new runtime and type-resolution branches.
- Explicit offsets are retained instead of rebound to the worker zone.
- Null/invalid patterns return null consistently before typed conversion.
- Same-name UDF shadowing and the existing FROM_UNIXTIME output change are documented.
- The supported inverse relationship depends on using compatible zones/patterns; arbitrary formatted output is not lossless.
Complete runtime path
Sql transform -> ZetaSQLEngine row projection -> recursive argument evaluation
-> ZetaSQLType BIGINT + ZetaSQLFunction UNIX_TIMESTAMP dispatch
-> pattern validation -> typed conversion / offset-aware parseBest -> epoch seconds
-> output SeaTunnelRow -> configured sink
FROM_UNIXTIME -> same formatter factory -> English text formatting
The old offset-loss, invalid-pattern and typed-null-pattern findings are addressed in the full current diff. Existing UDF dispatch remains in the default branch, so shadowing is an intentional compatibility change. Date resolution retains SMART adjustment and Java zone-resolution behavior; this does not introduce a stricter invalid-date or DST-ambiguity policy.
1.2 Compatibility Impact
Partially incompatible. A same-named custom UDF is bypassed and its result type is replaced by BIGINT. Existing FROM_UNIXTIME text output changes to English on non-English workers. Both migration pages describe the affected behavior and actions; other function names, options and checkpoint formats are unchanged.
1.3 Performance / Side-Effect Analysis
Formatters are immutable and shared in a concurrent map. The size check is a soft admission bound, not an atomic strict cap; no eviction means later misses may rebuild per row after saturation. This is the already-discussed SEZ9 cache follow-up, retained as non-blocking here rather than a new duplicate finding. No new thread or resource-owning path.
1.4 Error Handling and Logging
Malformed patterns and unparseable strings return null under the documented contract. Unsupported non-temporal types raise a typed transform error. No new logging of row values is added by this function.
No blocking source issues found. The existing non-blocking test-stability finding is summarized below.
Issue 1: Shared JVM defaults and wall-clock test assumptions
- Location:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLDateTimeFunctionsTest.java:334,353,666 - Problem description: The stability discussion already records JVM timezone/FORMAT-locale mutation and the no-argument wall-clock window. finally restores globals but does not isolate concurrent tests.
- Potential risk: CI reliability under timing or concurrent-run conditions.
- Best improvement: Use a shared resource lock or isolated execution for JVM defaults and retain explicit offset assertions. This restates the existing non-blocking stability finding; it adds no new blocker.
- Severity: Medium; non-blocking.
- Raised by another reviewer: No duplicate technical blocker is added.
2. Code Quality Assessment
2.1 Coding Standards
The method documentation explains typed values, nulls, offsets, unsupported input and SMART resolution. The cache comment's expectation of few patterns is an operational assumption, not a guarantee for row-supplied patterns.
2.2 Test Coverage and Test Stability
Test stability: Risk present. Fixed UTC/UTC+8 epochs, explicit-offset cases, null/invalid patterns and unsupported types have exact SQL-engine assertions. Tests restore global timezone and FORMAT locale in finally, but still assume no concurrent test mutates those JVM globals. The no-argument test uses a 60-second wall-clock window. Existing TestSQLIT now executes the new fixture; equality/round-trip relations strengthen the former NOT_NULL-only checks without assuming the container zone. The AT TIME ZONE example test uses the same zone as its JVM default, so its comment overstates independent detection of an ignored zone expression; the separate offset tests provide meaningful differing-offset coverage. No existing assertions are removed.
Local analysis: fetched the head, created independent branch seatunnel-review-12703, read the complete 10-file diff and traced affected callers with git show/git grep. No local compilation, unit tests, integration tests, E2E, containers, or job execution was performed, as requested. These are source-analysis conclusions; execution evidence is the current-head CI below.
2.3 Documentation Updates
English/Chinese function references cover supported forms, system-zone versus explicit-offset behavior, null/error policy, partial-date patterns, SMART dates and AT TIME ZONE usage. Migration entries now cover both UDF shadowing and FROM_UNIXTIME locale output. The earlier optional wording refinement to name the two locale-pinned functions explicitly remains optional; other formatter functions are outside this diff.
3. Architectural Soundness
3.1 Elegance of the Solution
Precise fix. The existing function dispatcher/type resolver and DateTimeFunction are the correct boundaries. Pinning locale at the shared formatter owner covers both directions. Adding a timezone parameter, broad date-family refactoring or a cache-policy redesign would expand scope beyond the remaining documentation fix.
3.2 Maintainability
Keep type dispatch, runtime dispatch and bilingual contracts synchronized; retain offset-aware parse ordering.
3.3 Extensibility
The existing dispatcher pattern supports later functions without engine or connector changes.
3.4 Historical-Version Compatibility
Rename an existing UNIX_TIMESTAMP UDF or adopt the built-in BIGINT contract, and update consumers expecting localized FROM_UNIXTIME text. No checkpoint migration is introduced.
4. Issue Summary
| Number | Issue | Location | Severity |
|---|---|---|---|
| 1 | Shared JVM defaults and wall-clock test assumptions | seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLDateTimeFunctionsTest.java:334,353,666 |
Medium (non-blocking) |
5. Merge Recommendation
Conclusion: Ready to merge after fixes
- Blockers — must be fixed
- No source blocker identified. No blocking source/documentation finding remains; wait for successful current-head Build and effective maintainer approval.
- Recommended fixes — non-blocking
- Issue 1: Use a shared resource lock or isolated execution for JVM defaults and retain explicit offset assertions. This restates the existing non-blocking stability finding; it adds no new blocker.
- Prior optional locale-wording and formatter-cache suggestions remain non-blocking; no wider date-function refactor is required.
Overall assessment: The final migration-note omission is closed. The full code path and strengthened regressions retain the earlier resolved correctness findings; pending CI is not a completed validation result.
Existing-review reconciliation: @SEZ9's issues 1/2/3/5/6/7/8 are addressed by pattern handling, documentation, UDF migration, offset preservation, type rejection and stronger integration assertions. Their cache concern remains the previously accepted optional follow-up. +1 to @SEPURI-SAI-KRISHNA's locale ownership analysis; getFormatter is the correct shared site. @SEZ9 offered approval after the locale migration note, but that stated intent is not an actual APPROVED event. Author replies have been incorporated into this single full review.
Head af865b17aad15b7ff5cf34eecfd4f6d8b32dbc75. Live base dev at 3ac2d1cec6aa7b3741c4dacdd23020f778e23c02; comparison ahead, ahead 7 / behind 0; merge state BLOCKED. Behind/diverged alone is recorded metadata, not a request to synchronize upstream. Checks: Signal pull request update = SUCCESS; Build = IN_PROGRESS
Current Build is IN_PROGRESS. Let the existing run finish rather than starting overlapping retries. Earlier-head cancellations are not this head's result, and branch drift alone does not establish a sync remedy.
Daniel has READ repository permission. This COMMENT records the technical conclusion; it is not an effective maintainer approval or a dismissal of any historical requested-changes entry. A write-capable maintainer owns the final repository approval gate.
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks again for the careful contribution. The CI fact in my preceding full review has changed: the previously pending Apache Build has completed SUCCESS on unchanged head af865b17aad15b7ff5cf34eecfd4f6d8b32dbc75. The previous review left CI as the sole technical blocker. It is now passing, so I am submitting an approval.
I checked the successful exact-head fork Build and all 96 job conclusions. All four JDK 11/17 unit-test legs and both transform IT parts on JDK 11/17 succeeded. Skipped jobs are not counted as executed coverage. No local build or test was run.
Merge recommendation
- Source blockers: none remain in my preceding full review.
- CI blocker: the previously pending check is now cleared. No extra contributor commit, sync or rerun is requested for this completed check.
- Non-blocking recommendations from that review remain optional.
- Effective repository approval/merge gate: GitHub currently reports
UNKNOWN/REVIEW_REQUIRED. Daniel has READ repository permission. This technical review does not claim to satisfy write-reviewer protection, dismiss another review or merge the PR; a write-capable maintainer must reconcile any remaining effective gate.
Overall: the source conclusion is unchanged and the previously missing CI evidence is now present. This is a CI-state follow-up, not a second full source review. Checked 2026-11-01T11:12:16.582246+00:00.
davidzollo
left a comment
There was a problem hiding this comment.
+1
LGTM
Thanks for your contribution!
Please ignore the following message if you have joined in the Slack~
To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace. Slack workspace link: https://s.apache.org/seatunnel-slack
apache#12703 added getFormatter, which already uses Locale.ENGLISH for FROM_UNIXTIME and UNIX_TIMESTAMP. Keep dev's FROM_UNIXTIME, use getFormatter in FORMATDATETIME too, remove the FROM_UNIXTIME doc sentence that now repeats dev's, and limit the incompatible change entry to FORMATDATETIME.
Purpose of this pull request
Add a
UNIX_TIMESTAMPbuilt-in SQL function to the Zeta SQL transform, the inverse of the existingFROM_UNIXTIME, as requested in #12699.Supported forms:
UNIX_TIMESTAMP()— current epoch seconds.UNIX_TIMESTAMP(dateTime)— a TIMESTAMP / TIMESTAMP_TZ / DATE column.UNIX_TIMESTAMP(string[, pattern])— parsed with an optional pattern (defaultyyyy-MM-dd HH:mm:ss); unparseable input returns NULL rather than raising. An explicit NULL pattern returns NULL.Motivation: epoch-second conversion for downstream sinks and SQL-dialect parity.
Changes (8 files, +315 lines, pure addition):
ZetaSQLFunction.java: register theUNIX_TIMESTAMPconstant and add the dispatch case.ZetaSQLType.java: resolve the return type as LONG (BIGINT).DateTimeFunction.java: implementunixTimestamp()— no-arg / typed datetime / string+pattern; resolved against the system time zone (inverse offromUnixTime). Uses onlyjava.time, no new dependency.SQLDateTimeFunctionsTest.java: 11 cases (no-arg, default/custom/date-only patterns, null input, unparseable, null pattern, numeric, LocalDateTime/LocalDate/OffsetDateTime).docs/{en,zh}/transforms/sql-functions.md: documentUNIX_TIMESTAMPafterFROM_UNIXTIME.func_unix_timestamp.conf+ mounted inTestSQLIT.Closes #12699
Does this PR introduce any user-facing change?
Yes — a new built-in SQL function. Pure addition; no existing function or behavior is changed.
How was this patch tested?
./mvnw -pl seatunnel-transforms-v2 test -Dtest=SQLDateTimeFunctionsTest ./mvnw -pl seatunnel-transforms-v2 spotless:checkUnit:
SQLDateTimeFunctionsTest— 16/16 pass. E2E:func_unix_timestamp.confadded underseatunnel-transforms-v2-e2e-part-2, mounted inTestSQLIT.Check list
docs/enanddocs/zhtransforms/sql-functions.md.incompatible-changes.mdto describe the incompatibility caused by this PR. — N/A, pure addition, no incompatible change.