Skip to content

fix: align OCT compatibility and result metadata - #28533

Merged
XuPeng-SH merged 2 commits into
mainfrom
codex/fix-oct-28465-28466
Sep 10, 2026
Merged

XuPeng-SH merged 2 commits into
mainfrom
codex/fix-oct-28465-28466

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement
  • Test and CI

Which issue(s) this PR fixes:

Fixes #28465
Fixes #28466

What this PR does / why we need it:

This PR finalizes the OCT compatibility fix on the current main branch. PR
#28450 (expression defaults, MORPC v60) is already merged; the old stacked
expression-default implementation and duplicate history are not included here.

Correctness

  • New OCT overloads return VARCHAR(65), matching MySQL metadata and allowing
    CTAS/view/client metadata to preserve the character result domain.
  • Existing overload identities 0..14 retain their original DECIMAL128
    result and executors. This protects persisted expressions and mixed-version
    execution from passing a DECIMAL result wrapper to the new VARCHAR executor.
  • String inputs use bounded MySQL-style decimal-prefix conversion: ASCII
    whitespace/signs, fractional and trailing text, invalid non-empty values,
    empty values (NULL), positive overflow, and negative overflow are handled
    without aborting a mixed-row query.
  • DATE/DATETIME use the year, TIME uses its signed hour, and binary literals
    retain their byte-oriented conversion. BINARY/VARBINARY/BLOB columns use
    their ordinary string-byte contents rather than being mistaken for HEX
    literal provenance.
  • DECIMAL64/128/256 values reach OCT through exact decimal text, avoiding the
    previous FLOAT64 precision loss above 2^53 and preserving unsigned/negative
    boundary behavior.
  • Finite FLOAT/DOUBLE values no longer fail on ordinary large values. The
    common DOUBLE range uses a bounded integer fast path; scientific notation
    follows the numeric-expression formatting contract, including rounding
    carry at the first integer-prefix digit.
  • Direct OCT operands in arithmetic are explicitly cast into the numeric
    operator lattice. The existing MatrixOne text + text -> CONCAT behavior
    is unchanged for ordinary text expressions.
  • New string OCT results are conservatively nullable because a valid empty
    non-NULL string produces SQL NULL; numeric/temporal/bit and legacy
    nullability contracts remain unchanged.

Rolling upgrade / protocol safety

The current main branch already uses MORPC v61 for index metadata provenance.
The new OCT overload identities therefore use MORPC v62. Admission is checked
at plan compilation, cached Run, and remote pipeline send/receive boundaries,
including nested persisted expressions (CHECK/default/generated/ON UPDATE).
Older persisted OCT identities remain executable; a newer OCT identity is
rejected with an explicit unsupported-version error when the negotiated
capability is below v62.

Performance and unhappy paths

The hot string path is one bounded prefix scan plus octal formatting, with no
per-row logging, retry, goroutine, lock, or unbounded allocation. Large finite
float conversion avoids temporary strings in the common range. Empty strings,
NULLs, selection masks, mixed rows, overflow, invalid prefixes, old serialized
plans, cached plans, and remote boundaries are covered by tests.

Validation

Passed locally on macOS arm64 / Go 1.26.4 using the repository CGo wrapper and
a freshly built matching native library:

  • Focused OCT function, binder, protocol, cached-run, and remote-boundary
    tests.
  • Full pkg/sql/plan/function, pkg/sql/plan, and pkg/sql/compile tests.
  • Focused -race OCT tests for function and compile packages.
  • go vet -mod=readonly for the changed packages.
  • Package-scoped golangci-lint for the changed packages: 0 issues.
  • make build-with-prebuilt-native NATIVE_BUILD_JOBS=8.
  • func_string_oct.test: 76/76, 100%, in two clean reruns with metadata
    ignored and one run with metadata checking enabled; no table residue after
    execution.
  • Independent SQL CTAS verification: OCT columns are VARCHAR(65), nullable
    for empty string/binary inputs, and values read back correctly.
  • git diff --check.

The full legacy create_table_as_select.sql fixture was also probed, but its
baseline result file has unrelated metadata drift in many existing cases
(DECIMAL/CHAR/TEXT widths and SHOW CREATE expectations), so its 86% result is
not attributed to this PR and no unrelated fixture changes are included.
The OCT-specific CTAS path was verified independently above. CI should provide
the authoritative Linux/multi-CN result for the final head.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Sep 9, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reviewed base d2b7563 through head 665ae76. I read the complete 10-file diff and traced OCT registration/evaluation, planner numeric consumers, VARCHAR(65) metadata/CTAS, binary-literal versus binary-column behavior, NULL/empty/mixed rows, prepared-expression provenance, and the updated UT/BVT fixtures. The ordinary-fix design gate is exempt. Current exact-head CI is green; I also checked the compatibility edge cases below against a local MySQL 8.4.10 reference instance.

[P1] Preserve DECIMAL input before applying OCT

Location: pkg/sql/plan/base_binder.go:5258 and the OCT overload set in pkg/sql/plan/function/list_builtIn.go

The binder still unconditionally casts DECIMAL64/DECIMAL128 OCT arguments to FLOAT64, and this PR adds no decimal overload. That loses integer precision before the new formatter. A reachable counterexample is:

SELECT OCT(CAST(18446744073709551615 AS DECIMAL(38,0)));

MySQL 8.4.10 returns 1777777777777777777777. Here the exact decimal is rounded by the binder to float64 value 18446744073709551616; octFloat formats that integer text and strconv.ParseUint rejects it, so a valid DECIMAL query terminates with an internal out-of-range error. Values above 2^53 can also silently select the octal representation of a neighboring integer. The existing 14.314 case does not disprove this because it is far below the precision boundary. Please keep decimal conversion exact through truncation and uint64/twos-complement handling, with 2^53±1, MaxInt64±1, MaxUint64, fractional, and overflow public-path cases.

[P1] Do not codify MySQL-incompatible finite-float overflow errors

Location: pkg/sql/plan/function/func_unary.go:8037 and test/distributed/cases/function/func_string_oct.result:31

The recent math.Trunc fix closes half-value rounding, but octFloat still parses the formatted value with ParseInt/ParseUint and returns an internal error outside those ranges. The BVT explicitly retains that error for OCT(10e50) and OCT(-10e50). MySQL 8.4.10 instead returns 1 and 1777777777777777777777 respectively; it also returns those same two boundary results for OCT(1e308) and OCT(-1e308). Thus the new result file makes CI green by asserting behavior that contradicts the compatibility target, and a mixed-row vector containing one large finite float still aborts the whole query. Please define the float-to-unsigned conversion at finite overflow, implement it without ParseInt range failures, and replace the error oracle with MySQL differential boundaries on both signs. I attempted to disprove this as an NaN/Inf-only corner, but ordinary finite DOUBLE literals reproduce it.

The VARCHAR(65) metadata, signed integer modulo formatting, TIME hour conversion, literal/column binary distinction, empty-string NULL behavior, and direct arithmetic casts matched the inspected MySQL controls. No concurrency, wait, restart, resource-ownership, or unbounded-growth path is introduced; the hot path remains one bounded scan plus formatting. The two numeric conversion gaps above remain correctness blockers even though this self-authored review is submitted as comment-only.

COMMENT

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Addressed the two P1 findings from review 5158047034 in dd6ea3a.

  • DECIMAL64/128/256 now reach OCT through an exact decimal-to-VARCHAR cast, reusing the existing integer-prefix converter. There is no FLOAT64 intermediate or new wire overload. Bit aggregates retain their existing coercion. Tests cover 2^53 boundaries, signed/unsigned limits, fractions, overflow, and nullable column binding.
  • Floating-point OCT uses numeric-expression text semantics. Large finite values such as +/-1e308 no longer return an internal range error. Scientific notation contributes its integer mantissa prefix. Ordinary DOUBLE values have a bounded arithmetic fast path, avoiding temporary text.
  • Updated the old OCT BVT error expectations and added exact-decimal column/NULL and large/tiny floating-point cases.

Validation on the final code:

  • Complete pkg/sql/plan/function and pkg/sql/plan suites: PASS, uncached.
  • OCT function/binder regressions with -race -count=1: PASS.
  • Temporary deterministic MySQL 8.0 oracle: 600 FLOAT column values and 600 DOUBLE expression values, both signs and broad exponent ranges: PASS. MySQL 8.4 conversion source was also checked. The external-oracle harness was not committed as a Docker-dependent UT.
  • git diff --check: PASS.
  • Scalar helper microbenchmarks, three 200ms samples: ordinary DOUBLE median ~63 -> 18 ns/op; negative DOUBLE ~82 -> 49 ns/op, one result allocation in both versions. This is not an end-to-end SQL benchmark.

Explicit compatibility boundary: MySQL itself uses different text budgets for DOUBLE expressions (22) and physical DOUBLE fields (24). For example, OCT(-4.5059201840559264e-5) returns the octal representation of -4, while storing that same value in a DOUBLE column and applying OCT directly returns 0. This patch consistently uses expression formatting; it does not infer SQL provenance from vector constness, which would make folding/materialization change results. Full emulation of this source-sensitive corner is not claimed or solved here.

The updated mo-tester BVT has not been executed against a new service on 55 in this turn. No local MatrixOne service was started. No CI wait or rebase was performed.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Force review conclusion: COMMENT (own PR; APPROVE/REQUEST_CHANGES are not allowed). Exact head: 51a1d75

Confirmed blocker

P1 — Changing existing OCT overloads breaks previously bound expressions across upgrade and mixed-version execution.

Locations: pkg/sql/plan/function/func_unary.go:7935, pkg/sql/plan/function/list_builtIn.go:8926; failure at pkg/container/vector/functionTools.go:595.

Counterexample: create a CHECK constraint containing OCT(a) on the previous revision, then upgrade and execute an INSERT against the existing table. The old catalog expression retains the old overload/result type (DECIMAL128), while the new implementation expects FunctionResult[types.Varlena]; execution can panic with wrong type for FunctionResultWrapper. The same mismatch can occur when a new AP projection is sent to an older receiver. Both revisions advertise protocol v58 and there is no OCT capability boundary.

Please preserve compatibility for previously bound OCT expressions with versioned overload identities or an explicit legacy path, and gate new overload transmission on receiver capability, including cached plans after downgrade. Add old-catalog CHECK and mixed-version projection regressions.

The two prior numeric findings (DECIMAL precision loss and large finite float failure) were verified fixed.

Test evidence / unverified risks

The blocker is a source-path proof; no upgrade or mixed-version cluster reproduction was run. Remaining gaps include prepared/error-then-success reuse, mixed runtime string metadata, full DECIMAL256 boundaries, SQL-level performance, fault injection, and compatibility/restore testing. Current BVT/CTAS artifacts passed, but normal Ubuntu UT was still in progress at inspection.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Force review of exact head 368a48df22db8bec0bec97cd32d84aba2728d1c2 against base 7c643f469b9162dec19b7f880e4cf6b2c12507d9. COMMENT only for this self-authored PR. One confirmed P2 metadata/DDL correctness blocker remains.

[P2] Mark the new string OCT overloads nullable even for NOT NULL inputs.

OctString now explicitly adds a NULL result for an empty non-NULL string (pkg/sql/plan/function/func_unary.go, the len(v)==0 branch). However, DeduceNotNullable in function.go:376–450 has no OCT exception and returns true when its input is NOT NULL. The binder installs that result at base_binder.go:6000. Thus this reachable case has contradictory metadata:

CREATE TABLE oct_nn(v VARCHAR(10) NOT NULL);
INSERT INTO oct_nn VALUES ('');
SELECT OCT(v) AS o FROM oct_nn; -- runtime value is NULL
CREATE TABLE oct_nn_copy AS SELECT OCT(v) AS o FROM oct_nn;

The SELECT expression is incorrectly marked NotNullable=true. CTAS directly consumes this flag through ctasExprCanBeNull (build_ddl.go:1563), which only exempts DATETIME casts, and constructs Default.NullAbility=false; it therefore declares a NOT NULL target for an expression that returns NULL. This is established from the exact-head binder/executor/CTAS source chain, not a claimed fresh live-server execution. The current empty-string executor test and return-width tests do not test nullability together with a NOT NULL source column.

Please make nullability deduction conservative for the new string-capable OCT identities (preserving the legacy behavior and optionally retaining precise numeric-overload nullability), then add a NOT NULL VARCHAR/VARBINARY source test with empty and non-empty rows plus CTAS/read-back metadata coverage. A numeric input control should remain available.

Other reviewed closures: the old 0–14 overload identities retain their DECIMAL128 executors; new calls use appended VARCHAR identities. Exact DECIMAL text avoids FLOAT64 precision loss, prefix sign/overflow handling is bounded, TIME uses the signed hour, and binary literals remain distinct from binary column bytes. The direct-OCT arithmetic cast avoids the existing text-concatenation rewrite. Admission, cached Run, and remote encode/decode all check the new v59 capability, including nested persisted expressions. NULL/mask/error paths use the existing vector wrapper ownership; no new goroutine, wait or unbounded retained resource was introduced. The documented tiny-DOUBLE expression-versus-field formatting difference is an explicit known compatibility decision, not a new finding here.

CI has no failed or running checks at the review snapshot, and git diff --check passed. Existing reported package/BVT evidence is noted; I did not rerun a full server or long tests. Green CI does not cover the NOT NULL source/NULL-producing OCT combination above.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review of exact head 518f0a2807e536018768c0f9565256c69b191dfb against base 2a6fe7f61358e846a20aafba3b50903a61608682. I read the complete review history and current full diff, and compared the post-368a48df22 changes. The previous blockers are closed: DECIMAL inputs retain exact text, finite floats no longer abort, overload IDs 0–14 keep the legacy DECIMAL128 ABI/executors, new OCT identities are fenced at compile/cache/remote boundaries, and string-capable OCT nullability now matches the empty-input NULL result (including CTAS coverage). Focused function/plan/compile tests and their race variants passed locally; the MySQL 9.6 controls for temporal, binary, overflow, and scientific-format cases matched the new expectations.

One rollout-safety blocker remains: this exact tree advertises a cumulative v61 capability while omitting the v60 implementation that is still in open PR #28450. The inline finding gives the concrete mixed-version sequence. The PR body itself says not to merge/release this head before #28450; that prerequisite needs to be made true in the reviewed commit, not left as an operational instruction.

Comment thread pkg/defines/const.go Outdated
MORPCLatestVersion = MORPCVersion59
MORPCVersion60 int64 = 60 // row-dependent expression defaults (provided by #28450)
MORPCVersion61 int64 = 61 // VARCHAR OCT overload identities
MORPCLatestVersion = MORPCVersion61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Do not advertise cumulative protocol v61 before the v60 implementation is present. MOProtocolVersion is the oldest-live-service capability, so declaring MORPCLatestVersion = 61 asserts that this binary implements every lower capability. This exact tree only reserves the v60 constant; the row-dependent-default admission/materialization code is still in open PR #28450. A reproducible rollout is: deploy this head first, then start rolling to a later binary containing #28450. During overlap the old node reports 61, so the cluster version remains >=61 and the new node may admit a schema such as b INT DEFAULT (a + 1) under #28450's version >= 60 gate. The old node can then plan an INSERT against that persisted default without #28450's VALUE_SCAN/materialization changes, defeating the gate and risking an error or an incorrect default value. The warning in the PR body is not a runtime fence. Please rebase this PR after #28450 lands (as the body requires), or use a genuinely contiguous allocation that does not make this standalone binary claim the missing v60 capability.

@mergify

mergify Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Re-review of 5dad3ee against main 9a5dd0c: no remaining concrete blocker found. COMMENT only for this self-authored PR.

The previous findings are closed:

  • Exact DECIMAL64/128/256 text reaches OCT without a FLOAT64 intermediate; the integer-prefix converter handles unsigned limits, fractional prefixes and signed overflow without aborting ordinary mixed rows.
  • Finite FLOAT/DOUBLE conversion has a bounded common-range fast path and scientific-text fallback, including the previously reported leading-digit rounding carry.
  • Persisted overload identities 0–14 retain the original DECIMAL128 return type and legacy executors. New calls resolve only appended VARCHAR identities; the serialized old-Obj/old-Typ test exercises the former wrapper mismatch rather than reconstructing a new registry type.
  • String-capable new identities are conservatively nullable, matching empty non-NULL input. NOT NULL VARCHAR/VARBINARY versus numeric controls now cover deduction, CTAS metadata and persisted read-back.
  • The cumulative-version blocker from the last review no longer applies: #28450 is merged, and the verified live base contains its v60 admission/materialization implementation and v61 provenance capability. This PR allocates OCT v62, not an implementation gap disguised by a higher version constant.

Other checked closures: ASCII prefix/sign handling, zero/empty/NULL, big-endian literal bytes versus binary-column text bytes, integer two's-complement conversion, DATE/DATETIME year and signed TIME hour, direct arithmetic coercion without changing ordinary text-plus, constant/column execution and selection masks. The new character result domain agrees with the MySQL OCT contract. Compile, cached Run, remote encode and remote decode fence new identities, including nested persisted/default/generated/CHECK/ON UPDATE expressions. The upgraded fast path does not reflect-walk the plan; older-capability validation is bounded by the expression graph.

This remains a focused compatibility repair, exempt from a separate feature-design artifact. The documented DOUBLE expression-versus-physical-field formatting corner is an accepted scope limitation: this implementation consistently uses expression formatting, not vector constness. I am not claiming complete emulation of MySQL's provenance-sensitive corner.

Evidence: read all current changed hunks, historical reviews/inline findings, vector wrapper/null-mask consumers and protocol walker, and the current UT/BVT result oracles. Reused the reported macOS arm64/Go 1.26.4 source-matched package, focused race, vet/lint/build, 76/76 OCT fixture reruns and independent CTAS evidence; I did not rerun native tests, start a server, or wait for CI. Full legacy CTAS fixture success and a live mixed-old/new-CN upgrade/restore run are not established by this review. The PR's unrelated-drift attribution for the broad CTAS probe is author-reported, not independently reproduced here. None supplies a new concrete blocker for the reviewed OCT closure.

Live head/base were rechecked before submission and are unchanged. No production/test edits.

This branch was previously deployed

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

Labels

kind/bug Something isn't working kind/enhancement kind/test-ci size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

3 participants