Repository navigation
fix(sql): harden FORMAT numeric and locale handling - #28508
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Force deep review of exact head 28716c1a174273d24400c74435319ada0987eb0a against base cd04bb4c1af5bc595e2147dc645dfa754f4c395b. COMMENT only; CI readiness intentionally waived. Two P2 items remain: a confirmed numeric-domain rounding regression, and missing public SQL regression proof.
The malformed-input bounds checks, zero-scale rounding for exact decimals, sign preservation, 30-place cap, leading-prefix normalization, immutable case-insensitive locale dispatch and 3/2 Indian grouping address the reported examples. This is a focused correction of existing FORMAT behavior, not a new syntax/major-refactor design gate. I reviewed all three changed files, both registered VARCHAR overloads, wrapper NULL/error handling and the existing FORMAT BVT fixture. No new persistent/wire/auth contract, goroutine, lock, external handle or shared mutable per-call state is introduced.
[P2 / validation] Extend test/distributed/cases/function/func_string_format.test and its result with the new public contracts. The PR changes no BVT and explicitly reports no SQL-server/BVT execution. Internal formatter/wrapper tests cannot prove type coercion preserves DECIMAL versus DOUBLE/string semantics, nor PREPARE and stored mixed-row behavior. Add the original malformed-number/empty-scale cases, scale cap, non-default locale casing and Indian grouping, plus the typed halfway controls in the inline finding; execute normal comparison mode, verify cleanup, and rerun on the same instance. Existing formatter BVT already provides a reusable fixture; no new heavy harness is needed. The absence of a local server explains but does not close this mandatory public-path validation gap.
Q1: per-call buffers are GC-owned and wrapper result appends propagate allocation errors. Q2: parsing, rounding and grouping use finite scans with no added wait/cancellation dependency. Q3: scale-derived output is capped at 30, ordinary output remains linear in input length, scientific expansion is bounded by float64, and locale maps are initialized once and read-only. No confirmed new leak/hang or superlinear performance regression was found. No full performance benchmark is claimed.
Independent validation: exact-head format.go plus the complete exact-head format_test.go passed with GOWORK=off go test -mod=readonly -v -count=1 -timeout=60s <files> (0.525s), and -race -count=1 (1.327s). A separate halfway counterexample test against the exact formatter failed for 1.25/1, 1.25e0/1, 2.5e0/0, returning 1.3/1.3/3 rather than approximate/string-domain 1.2/1.2/2. The MySQL oracle is derived from its authoritative source, not a live MySQL run: the local port 3306 connection was unavailable. The author-reported function-package normal/race passes are noted, not independently rerun. Initial file-test invocation hit checkout vendoring inconsistency; using the prescribed readonly module mode resolved it without source changes. No full CGo function package, BVT, numerical coverage or CI pass is claimed.
| continue | ||
| } else if v == '.' && number[1] != '.' { | ||
| continue | ||
| roundUp := decimals < len(fraction) && fraction[decimals] >= '5' |
There was a problem hiding this comment.
[P2] Preserve the approximate/string rounding domain instead of applying half-up universally
The new digit test rounds every halfway value away from zero, including inputs that MySQL treats as approximate numbers. SELECT FORMAT('1.25',1) and FORMAT(1.25e0,1) should produce 1.2, while exact DECIMAL FORMAT(1.25,1) produces 1.3; the current common routine returns 1.3 for all three. The VARCHAR counterexample is directly reachable without any disputed numeric cast. This replaces the old ParseFloat/FormatFloat branch that returned 1.2 for the positive string case.
MySQL explicitly separates DECIMAL/INT from STRING/REAL in Item_func_format::val_str_ascii; the latter calls my_double_round, which uses rint. The exact-head helper probe reproduces 1.3 for GetNumberFormat("1.25","1","en_US") and for "1.25e0", and 3 for "2.5e0" at scale 0.
Retain the source numeric category through overload/coercion and apply the appropriate rounding rule before grouping. Do not merely change all inputs to ties-to-even, which would break the exact-decimal fix. Add DECIMAL, DOUBLE/scientific and VARCHAR halfway controls through the real SQL path, including negative values and mixed rows.
aunjgr
left a comment
There was a problem hiding this comment.
Reviewed exact head 28716c1a174273d24400c74435319ada0987eb0a against cd04bb4c1af5bc595e2147dc645dfa754f4c395b. Requesting changes for one confirmed numeric-domain rounding regression.
The three-file diff and FORMAT wrapper were reviewed. Input bounds, locale lookup, grouping and scale capping do not present another confirmed blocker. However, the new digit-string round-up path applies exact-decimal rounding to approximate/string inputs as well.
An isolated test used this exact format.go unchanged:
GetNumberFormat("1.25", "1", "en_US")returns1.3.GetNumberFormat("1.25e0", "1", "en_US")returns1.3.GetNumberFormat("-1.25e0", "1", "en_US")returns-1.3.
MySQL routes STRING/REAL FORMAT operands through my_double_round, which uses rint (ties-to-even in the usual rounding mode); the approximate results are 1.2, 1.2, and -1.2. Its FORMAT dispatch uses decimal rounding only for DECIMAL/INT. Exact decimal FORMAT(1.25, 1) should still yield 1.3. The old positive scale-1 formatter returned 1.2 for the string input; this change regresses that case while correcting exact-decimal rounding.
Please preserve DECIMAL versus REAL/string semantics at the binding/execution boundary and add typed halfway controls. The helper reproduction exited 1; this is not a claimed live MySQL or MatrixOne SQL-server run. Existing package/race/static evidence was reused, and applicable exact-head CI is passing.
| continue | ||
| } else if v == '.' && number[1] != '.' { | ||
| continue | ||
| roundUp := decimals < len(fraction) && fraction[decimals] >= '5' |
There was a problem hiding this comment.
[P2] Preserve the input numeric domain when rounding FORMAT. This unconditional digit >= '5' increment makes FORMAT('1.25', 1) and FORMAT(1.25E0, 1) return 1.3, whereas MySQL's STRING/REAL path uses my_double_round/rint and gives 1.2 under the usual ties-to-even mode. Exact DECIMAL FORMAT(1.25, 1) should remain 1.3. The wrapper currently erases the source domain into strings, so changing this condition globally cannot satisfy both contracts. Preserve the domain and add DECIMAL, DOUBLE/scientific, VARCHAR and negative halfway controls. Exact-helper reproduction and primary-source links are in the review body.
50283f0 to
e259a22
Compare
…eper ticker" This reverts commit e259a22.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Force review conclusion: COMMENT (own PR; APPROVE/REQUEST_CHANGES are not allowed). Exact head: 0644bd9\n\n## Confirmed blocker\n\nP1 — Persisted FORMAT expressions bypass the v59 pipeline fence.\n\nLocations: ; relevant persistence/consumer locations , , base and base ; panic at .\n\nCounterexample: create on a new CN while the common protocol remains v58, then insert into the existing table through an older CN. The typed expression is persisted with a BIGINT argument/old overload, loaded unchanged, and executed by the older string-only FORMAT implementation; its Varlena accessor can receive an 8-byte BIGINT payload instead of the required 24 bytes and panic. The local catalog path does not pass through the new v59 remote gate (). Downgrade exposes the same mismatch.\n\nFix: fence creation of persistent typed FORMAT expressions before catalog side effects and define downgrade behavior; preserve a compatible legacy overload/path or gate new semantics on receiver capability. Add old-catalog CHECK/generated-expression and mixed-version projection regressions.\n\nPrior findings (exact/approximate rounding, public SQL regression, typed numeric remote pipeline) were verified fixed.\n\n## Test evidence / unverified risks\n\nNo mixed-version/downgrade reproduction was run. Remaining gaps: Decimal128/256 boundaries, NULL scale/locale, selected rows, error-then-success reuse, same-instance BVT/teardown, SQL performance, and restore/compatibility matrix. Current CI/BVT passed on the exact head, but compatibility jobs were skipped and the normal Ubuntu UT was still in progress at review time.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Force review conclusion: COMMENT (own PR; APPROVE/REQUEST_CHANGES are not allowed). Exact head: 0644bd9
Confirmed blocker
P1 — Persisted FORMAT expressions bypass the v59 pipeline fence.
Locations: pkg/sql/plan/function/func_binary.go:6305; relevant persistence/consumer locations pkg/sql/plan/build_ddl.go:3681, pkg/vm/engine/types.go:190, base pkg/sql/plan/build_constraint_util.go:187 and base pkg/sql/plan/function/func_binary.go:6310; panic at pkg/common/util/unsafe.go:88.
Counterexample: create CHECK (FORMAT(a, 0) = '1') on a new CN while the common protocol remains v58, then insert into the existing table through an older CN. The typed expression is persisted with a BIGINT argument/old overload, loaded unchanged, and executed by the older string-only FORMAT implementation; its Varlena accessor can receive an 8-byte BIGINT payload instead of the required 24 bytes and panic. The local catalog path does not pass through the new v59 remote gate (pkg/sql/compile/remoterun.go:2060). Downgrade exposes the same mismatch.
Fix: fence creation of persistent typed FORMAT expressions before catalog side effects and define downgrade behavior; preserve a compatible legacy overload/path or gate new semantics on receiver capability. Add old-catalog CHECK/generated-expression and mixed-version projection regressions.
Prior findings (exact/approximate rounding, public SQL regression, typed numeric remote pipeline) were verified fixed.
Test evidence / unverified risks
No mixed-version/downgrade reproduction was run. Remaining gaps: Decimal128/256 boundaries, NULL scale/locale, selected rows, error-then-success reuse, same-instance BVT/teardown, SQL performance, and restore/compatibility matrix. Current CI/BVT passed on the exact head, but compatibility jobs were skipped and the normal Ubuntu UT was still in progress at review time.
XuPeng-SH
left a comment
There was a problem hiding this comment.
Force deep review of d13429a against base/merge-base 7c643f4. COMMENT only because this is my own PR.
Conclusion: no new confirmed blocker. This is hardening of the existing FORMAT contract, not a new feature requiring a separate feature-design artifact; no design-gate blocker is raised.
The previous concrete findings are closed in this head: exact INTEGER/DECIMAL and approximate REAL/string rounding are separated; typed arguments are detected and rejected below MORPC v59 at sender preparation and receiver decoding; CHECK, generated columns, DEFAULT, ON UPDATE and CTAS-default expressions are rewritten to the historical VARCHAR argument representation before folding. The catalog-versus-transient rounding distinction is explicitly documented and covered by serialization/execution tests. I am not treating old, unmerged candidate catalogs as a supported migration source.
Reviewed numeric prefix/scale scanning, signed rounding/carry and zero handling, scientific overflow/underflow, empty/invalid input, NULL argument handling, constant/vector access, case-insensitive locale fallback and Indian grouping, result-allocation failures, protocol detection and catalog consumers. Scale is bounded at 30; floating expansion is float64-bounded; typed exact values have bounded numeric widths. Locale maps are initialized once and subsequently read-only, with no new per-call shared mutable state, goroutine, wait or external resource. The public regressions exercise typed/string domains, FLOAT versus DOUBLE, mixed rows, repeated PREPARE/EXECUTE, and catalog INSERT/UPDATE plus teardown.
Evidence: git diff --check passed. Existing author normal/race evidence and prior numerical review findings were inspected and reused where relevant; current CI shows successful SCA, coverage and multi-CN BVT checks, while the ordinary Ubuntu UT remains in progress and upgrade jobs are skipped. No long tests or live mixed-binary/downgrade topology were run by this review. A real mixed-binary catalog/reused-plan smoke test remains useful follow-up evidence, not a newly demonstrated code defect. In particular, the plan serialization tests must not be described as execution against an actual older binary.
Summary
Fixes #28213
Fixes #28475
Fixes #28476
Fixes #28478
Fixes #28480
Harden the shared
FORMAT()implementation for numeric-string conversion,rounding, decimal-place parsing, and locale dispatch.
Root causes
approximate/string inputs.
Indian grouping were handled inconsistently.
pre-v59 receiver would therefore reinterpret a fixed numeric vector as
Varlena and could panic during a rolling upgrade.
Design
string values on the approximate ties-to-even path.
case-insensitive locale dispatch with dedicated
3,2,2...Indian grouping.FORMATarguments.Both sender preparation and receiver decoding reject a plan below v59, so a
reused/prepared plan cannot reach an old string-only receiver. Numeric values
in transient queries retain their typed rounding semantics.
generated-column, DEFAULT, ON UPDATE, and CTAS default expressions before
constant folding. Local catalog execution bypasses the pipeline fence, so
this applies at every protocol version and remains safe after downgrade.
Persisted FORMAT retains approximate rounding (2.5 -> '2'); transient exact
numeric FORMAT retains half-up rounding (2.5 -> '3'). This does not migrate
typed catalog expressions written by earlier, unmerged PR candidates.
Validation
Latest catalog compatibility fix:
pkg/sql/plantests andgo vet ./pkg/sql/planpassed.DECIMAL and DOUBLE, two/three arguments and nested calls; verified legacy
catalog rounding and typed projection behavior, DEFAULT/ON UPDATE/CTAS.
UPDATE. The new fixture and a real mixed-binary/downgrade topology have not
been run locally; CI validation remains pending.
Earlier numeric/remote compatibility validation:
0e7e72ff) completed the distributed FORMAT BVT 263/263with no failed, ignored, or abnormal cases (run 34362979598); the rebased
head has a new CI run pending.
main, normal and-raceCGo suites passed forpkg/pb/plan,pkg/sql/compile,pkg/sql/plan/function,pkg/vectorize/format, andpkg/queryservice/client.FORMAT, exact and approximate numeric inputs, protocol v58 rejection, and
v59 round-trip acceptance.
numeric type coverage, and string-function controls.
git diff --checkpassed.Test plan
Run the formatter/function unit suites and the distributed
test/distributed/cases/function/func_string_format.testfixture in normal andrace modes. During a rolling upgrade, verify that a coordinator with a typed
numeric FORMAT plan returns a compatibility error while any live receiver is
below MORPC v59; once all peers are v59, verify the exact/approximate rounding
and locale results remain unchanged.