Skip to content

fix(sql): preserve temporal conversion warnings - #31746

Merged
XuPeng-SH merged 10 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/2e19051e411d967b81b509132a8abd4f7dade1ded60b4c83605a3fbdc18bb9f7
Oct 29, 2026
Merged

XuPeng-SH merged 10 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/2e19051e411d967b81b509132a8abd4f7dade1ded60b4c83605a3fbdc18bb9f7

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

What this PR does / why we need it:

Invalid temporal text in DATE, DATETIME, TIME and DATE_FORMAT expressions returns the appropriate NULL or recoverable TIME result with warning 1292, including mixed rows and prepared statements. Preserve diagnostics through expression evaluation, filtering, folding and remote execution, while keeping assignment and other existing conversion policies separate.

This builds on #30547, which returned NULL for invalid DATE and DATETIME expressions but explicitly left warning 1292 parity out of scope.

Validation on macOS arm64 includes function, colexec, plan, compile, rule and filter package tests; focused prepared-statement tests; two normal-comparison runs each of the affected DATE and temporal consistency BVT files; MySQL 8.0.46 comparison; and a two-CN test of one peer producing and returning projection diagnostics. The function BVT directory did not fully pass: two timestamp assertions failed in a timezone-order-dependent case. Multi-CN coverage does not test coordinator exchange or simultaneous production by multiple peers. Wire metadata and temporal-specific max_error_count=0/1 combinations were not newly verified.

A single-CN warm-cache valid DATE column predicate comparison measured a 4.9% median increase (five samples); this does not establish performance across other workloads or topologies. Invalid DATE constants incur approximately 3.04 µs and 1084 bytes per row for diagnostics. CI passed at 161acd120e8aacd6affbb04f3f90ed4f7e36d103 (run 40862615124).

Repair validation at 161acd120e8aacd6affbb04f3f90ed4f7e36d103 (macOS arm64, Go 1.27.1): new full package runs for plan, MongoDB, EXPLAIN, Substrait and compile passed with mo-cgo-test -vet=all -count=1. Focused -short -tags=matrixone_test -covermode=set -cover regressions passed, as did temporal SQL integration (including binary prepared statements and SQL PREPARE/EXECUTE) and TestIssue30537TemporalWarningsPeerCN with forced peer placement. Incremental golangci-lint over the PR package closure reports 0 issues. Function, colexec and rule package results are reused for their unchanged kernel/executor inputs. The repair preserves safe temporal constant planning, strict TIME comparison policy, MongoDB DATETIME predicate pushdown and failure-safe test cleanup. Full Linux Compose BVT and repository-wide coverage were not rerun locally.

Prepared GAPFILL repair validation at e3cf275e9bc51c8a07c45cf8de3ec77f51be60b5 (macOS arm64, Go 1.27.1): reproduced missing DATE/DATETIME bounds and an empty-range query returning 3 rows directly but 0 through parameterless binary preparation. Runtime-constant bounds now survive PREPARE; private grid evaluation preserves WHERE diagnostic ownership. New normal package runs for plan, timewin, EXPLAIN and compile passed with mo-cgo-test -vet=all -count=1; temporal SQL integration verifies direct, binary prepared and SQL PREPARE/EXECUTE results on empty and partitioned input, including cached repetition. A bound reset test covers invalid/valid/invalid inputs without extra warnings. Incremental golangci-lint on the three changed packages reports 0 issues. Earlier CI and kernel/remote validation are reused for unchanged inputs; full Linux Compose and coverage were not rerun locally for this repair.

@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 →

@XuPeng-SH XuPeng-SH 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.

mo-bot review · mo-bot-local · review

Commit: 161acd120e8aacd6affbb04f3f90ed4f7e36d103

Assessment: request_changes

The warning changes introduce a correctness regression in parameterless prepared GAPFILL queries.

Model: gpt-6-astra / xhigh

Session: 01a1869d-999c-7481-b340-ae4a63e8cee4 · slot 1 · generation 2

  • P2 pkg/sql/plan/apply_indices.go:1231: PREPARE a GAPFILL query with literal DATETIME range boundaries and no parameter markers, then EXECUTE it when no rows match the range.
    Impact: The new volatility classification makes bound inference reject the temporal casts. EXECUTE then returns no rows instead of synthesizing the bounded buckets. Preserve runtime-constant bound eligibility separately from diagnostic relocation, and add a parameterless prepared regression.
    Evidence: base_binder.go:4912 skips temporal materialization during PREPARE; query_builder.go:10208 and :10305 consequently discard the bounds. frontend/computation_wrapper.go:1629 only performs source rebinding when numParams > 0. colexec/timewin/timewin.go:306 requires bounds to synthesize empty-input buckets. The base revision accepted these casts. Detailed source trace and an unexecuted SQL reproducer are retained in source-review.md and probe_prepared_gapfill.sql.

Validation:

  • Verified frozen head/base, clean source, complete patch identity and discussion coverage; source-check.log and checks/1793278048471430335-2.json record exit 0.

  • Isolation preflight passed; preflight.log and checks/1793277934795947210-2.json record exit 0.

  • Supplied exact-head CI reports successful build, UT, coverage, SCA and both substantive Compose BVT jobs.

Limitations:

  • No local Go tests or SQL reproduction executed; the finding is established by source tracing.

  • Raw CI logs were not supplied. Author-reported performance and topology checks were not independently reproduced.

@iamlinjunhong

Copy link
Copy Markdown
Contributor Author

Addressed the parameterless prepared GAPFILL finding in commit e3cf275e9bc51c8a07c45cf8de3ec77f51be60b5.

Bound inference now uses runtime constancy independently of diagnostic relocation, preserving literal temporal boundaries through parameterless PREPARE. The inferred grid copies evaluate with a private warning probe; the original WHERE predicates retain statement diagnostics.

The regression reproduced missing DATE/DATETIME plan bounds and 3 expected empty-range buckets becoming 0 with binary preparation. The added frontend regression now verifies direct execution, parameterless binary preparation and SQL PREPARE/EXECUTE, twice per prepared statement, for both empty input and partitioned input. Invalid/valid/invalid bound reset coverage also verifies that grid evaluation does not publish warnings. Complete plan, timewin, EXPLAIN and compile package tests with vet, the temporal SQL integration test, and incremental lint passed on macOS arm64 with Go 1.27.1.

@XuPeng-SH

XuPeng-SH commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: e3cf275e9bc51c8a07c45cf8de3ec77f51be60b5

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH 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.

mo-bot review · mo-bot-local · review

Commit: e3cf275e9bc51c8a07c45cf8de3ec77f51be60b5

Assessment: approve

The prior prepared GAPFILL finding is resolved. Reviewed the complete delta, affected consumers and discussion; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

Validation:

  • Verified frozen head/base, unchanged source, patch identity and coverage of all five discussion entries. source-check.log and checks/1793285858133771892-4.json record exit 0.

  • Isolation preflight passed: preflight.log and checks/1793285472698515868-3.json record exit 0.

  • Reused supplied current-head CI results: successful build, UT, static analysis, coverage and both substantive Compose BVT jobs.

  • Saved review-plan.md, source-review.md, discussion-assessment.json and validation-manifest.json.

Limitations:

  • No local product tests executed; raw CI and author validation logs were not supplied.

  • Author-reported performance, temporal warning-retention combinations and additional coordinator/peer topology combinations were not independently reproduced.

@mergify mergify Bot added the queued label Oct 29, 2026
@mergify

mergify Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

2 h 18 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Thu 29 Oct, 15:00 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 17:17 · 2acec60

Reason

Pull request #31746 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Merge conditions: 2 of 3 met

This pull request

Condition Required by
✅ #review-threads-unresolved = 0 GitHub branch protection
✅ github-review-approved GitHub branch protection

The batch, tested in place

Condition Required by
❌ any of: check-neutral = CI Required, check-skipped = CI Required, check-success = CI Required GitHub branch protection

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

  • Requeue this pull request

Times in UTC · dashboard · how the merge queue works

@XuPeng-SH
XuPeng-SH merged commit 1c80f16 into matrixorigin:main Oct 29, 2026
27 of 28 checks passed
@mergify mergify Bot added dequeued and removed queued labels Oct 29, 2026
gouhongshen added a commit to gouhongshen/matrixone that referenced this pull request Oct 29, 2026
Resolve the PR matrixorigin#31739 merge conflict against main (969998e).

Main advanced with matrixorigin#31628 (FK rebind to surviving keys), matrixorigin#31738,
matrixorigin#31746, matrixorigin#31766, matrixorigin#31767, matrixorigin#31768, matrixorigin#31777. The only content conflict is
pkg/sql/plan/build_ddl_test.go: both sides appended independent test
functions after TestSessionDatabaseNullability. Keep both: this PR's
TestBuildCTASUnsignedDecimal{Attribute,SetOperation}Provenance and
main's FK-rebind tests (TestLegacyFkDoesNotProtectSecondaryIndexDrops,
TestStaleClaimRequiresRealCoveringKey,
TestDropPrimaryKeySelfReferenceRebindAddressesOriginalTable,
TestAlterDropPrimaryKeyRebindsToSameStatementUnique).

Everything else auto-merged with disjoint hunks:
- pkg/common/moerr/error{,_no_ctx}.go: this PR's
  ErrOutOfRangeValueForColumn (20211) and main's ErrDataBranchConflict
  (22501) occupy different code groups.
- pkg/sql/plan/build_ddl.go: this PR's CTAS default/attribute code
  (genAsSelectCols..finalizeCTASDefaults) vs main's FK-rebind region
  (checkDropReferencedKeyForeignKeyDependency..buildAlterTableInplace).
- pkg/sql/plan/base_binder.go, build_alter_table.go, query_builder.go,
  pkg/vm/engine/disttae/txn_table.go: disjoint regions.
XuPeng-SH pushed a commit that referenced this pull request Oct 30, 2026
…#31739)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #30940

## What this PR does / why we need it:

### Problem

`DECIMAL` column declarations silently dropped the parsed `UNSIGNED` and
`ZEROFILL` attributes:

- `DECIMAL(10,2) UNSIGNED` accepted and stored negative values under
every `sql_mode`, where MySQL rejects them with `ERROR 1264 (22003) Out
of range value`.
- `DECIMAL(10,2) ZEROFILL` produced no zero-padded output, and `SHOW
CREATE TABLE` / `information_schema.columns.COLUMN_TYPE` lost both
modifiers.
- `CAST(x AS DECIMAL(p,s) UNSIGNED|ZEROFILL)` was accepted, which MySQL
rejects outright with `ERROR 1064`.

### Root cause

Three coupled defects:

1. The plan-layer DECIMAL conversion (`getTypeFromAstWithoutCharset`)
selected decimal64/128/256 by precision and scale only, discarding the
parsed attributes, so the attribute never reached the persisted type,
assignment admission, or any presentation surface.
2. With no attribute on the type domain, every assignment path
(INSERT/UPDATE/LOAD/REPLACE/VALUES) had no unsigned rule to enforce,
SHOW CREATE / information_schema / result metadata had nothing to
render, and the CAST target grammar accepted spellings MySQL forbids.
3. The bootstrap upgrade framework had no versioned entry able to
reconcile persisted `information_schema.COLUMNS` view text on existing
clusters, and no admission gate for legacy CDC tasks during that
crossing.

### Changes

- **Attribute carrier**: `plan.Type.numeric_attributes` (proto field 14)
carries UNSIGNED/ZEROFILL from DDL through persistence, catalog cache,
table functions, arrowbridge/external readers, checkpoint tooling and
sysview.
- **Unsigned enforcement**: every assignment admission path enforces the
unsigned domain — strict mode rejects negatives with `ERROR 1264
(22003)` atomically (no partial writes), non-strict saturates to the
lower bound with a 1264 warning, `IGNORE` accepts; `ZEROFILL` implies
`UNSIGNED`. Executor cast saturates to the unsigned domain with scale
widening before negation.
- **Presentation**: SHOW CREATE and COLUMN_TYPE render the modifiers
(`decimal(10,2)`, `decimal(10,2) unsigned`, `decimal(10,2) unsigned
zerofill`); zero-padding is applied on all six decimal
serialization/export sites (text rows ×2, binary rows ×2 including
prepared, CSV and JSONLINE export) plus result-column display metadata.
- **CAST grammar**: `CAST(... AS DECIMAL(p,s) UNSIGNED|ZEROFILL)` is
rejected with `ERROR 1064 (42000)`, matching MySQL.
- **Upgrade crossing**: new version 4.0.18 (offset 1) one-shot
`information_schema.COLUMNS` reconciliation entry with legacy-CDC
admission gating, retained-target recheck, frozen-offset preservation
(`MinUpgradeVersion 4.0.7`, `RequiredProtocolVersion 126`), so upgraded
clusters decorate their persisted view text exactly once.

### Validation

- Primary regression, assigned base vs fixed: identical 8-section SQL
script plus server-side-prepared binary-row probe run against isolated
services built from (a) the unaltered base `3cf38889bc` (every defect
reproduced: negatives stored, modifiers dropped, no padding, CAST
accepted) and (b) this change (strict `ERROR 1264 (22003)` with zero
rows stored, non-strict clip to `0.00` + Warning 1264, modifiers
retained in SHOW CREATE/COLUMN_TYPE for masks 0/1/3, zero-padded text
and binary wire, both CAST spellings `ERROR 1064`, signed/NULL controls
unchanged).
- Focused BVT
`test/distributed/cases/dtype/decimal_unsigned_zerofill.test` (144
statements: strict/non-strict/IGNORE, modifier masks, wide widths,
defaults, UPDATE, NULL, CAST rejection, persistence, snapshot
compatibility): `TOTAL 144 SUCCESS 144 SUCCESS RATE 100%`; `mo-tester`
result regeneration byte-identical.
- Upgrade legs: `go test ./pkg/embed/ -run 'TestColumnsUpgrade'` — 7/7
PASS, including an ablation leg proving the 4.0.18 entry is solely
responsible for decoration (background COLUMNS maintenance suppressed,
undecorated predecessor verified) and a post-replacement-crash leg
proving view-content and tenant-progress roll back together with
idempotent restart replay; plus `go test ./pkg/bootstrap/...`, `go test
./pkg/hakeeper/`, and the v4_0_18 commit-fence unit subcase, all green.

### Residual risks

- The background `information_schema.COLUMNS/TABLES` maintenance walker
(kept enabled in production) also converges view text over time; the
upgrade entry owns the deterministic crossing and the ablation leg
proves its sole responsibility, but real-cluster non-upgrade convergence
remains upstream-owned behavior.
- Evidence scope: focused BVT and affected-package suites are green; the
full distributed dtype suite is left to CI. Signed-DECIMAL controls in
the focused file and sweeps show no behavior change for unmodified
columns.


### CI fix update (2026-10-29, commit 74a4105)

CI run 40845538549 at the previous head failed Matrixone UT Coverage (4
tests) and multi-CN e2e BVT (3 rows); all were caused by this PR and are
fixed in `74a4105d94`:

- **Bootstrap upgrade chaining**
(`pkg/bootstrap/service_upgrade_tenant.go`,
`pkg/bootstrap/custom_upgrade.go`):
`MaybeUpgradeTenant`/`UpgradeOneTenant` planning stopped at the frozen
consolidated v4.0.7 terminal entry, so tenants on older versions never
received the forward v4.0.18 upgrade and tenants already at 4.0.7
skipped it. Both paths now re-plan and run the v4.0.7 crossing on demand
until no pending v4.0.7 upgrade remains, and the frozen terminal entry
is skipped so the forward version still executes. Fixes
`TestCollationsMetadataUpgrade`,
`TestV407LoginRepairsTenantCreatedAfterUpgradeSnapshot`,
`TestCallerOwnedTenantUpgradeRollsBackAndRetries`,
`TestCatalogVersionOrderingUsesSemanticVersionAndOffset`.
- **Stale test expectations**
(`pkg/embed/catalog_view_identity_test.go`,
`pkg/embed/catalog_upgrade_paging_test.go`): assert the semantic final
version instead of hardcoded `4.0.7`; injected version samples
retargeted to 4.1.9/4.1.10/4.1.11 to preserve the
semantic-vs-lexicographic ordering check.
- **BVT expected results** (`test/distributed/cases/dml/show/show.test`,
`zz_accesscontrol/account_restricted.sql`): spliced the
unsigned-decimal-decorated `information_schema.COLUMNS` SHOW CREATE DDL
(Create View descriptor 18848 chars, +209) into the three expectations;
fixes show.test row 295 and account_restricted.sql rows 55/113.

Local verification: pkg/bootstrap package suite green; both embed tests
pass with `-v`; focused `decimal_unsigned_zerofill` BVT 144/144 pass via
mo-tester against a locally built instance; the three spliced SHOW
CREATE rows are byte-exact (18848 chars) against the live upgraded
instance.


### CI fix update #2 (2026-10-29, commit 0a05d68)

CI run 40862553192 at head 74a4105 failed `SCA Test on Linux/arm64`
(job 123409348216): `make static-check-selected` reported 9
static-analysis findings, all in files owned by this PR. Fixed in
`0a05d68642`:

- `pkg/container/arrowbridge/staging_text_test.go`: gofmt(simplify) —
collapse `decimal128.Num{}` to `{}` in the composite literal.
- `pkg/sql/plan/function/func_cast_unsigned_decimal.go`: ineffassign —
drop the dead `outcome` initializer (both classifier branches always
assign).
- `pkg/sql/plan/function/func_cast_unsigned_decimal_test.go`: two
ineffassign findings — discard results reassigned before use, rescope
the second JSON admission result.
-
`pkg/vm/engine/disttae/cache/catalog_column_update_numeric_attributes_test.go`:
prealloc — build the 5-column fixture slice in a single literal with
full capacity.
- `pkg/bootstrap/service_upgrade_crossing_test.go`: unused `inTxn` field
and `executionLog` accessor removed.
- `pkg/embed/upgrade_columns_4_0_18_test.go`: unused `readColumnsRoute`
/ `waitColumnsVersionReady` helpers and the orphaned `testify/assert`
import removed.

No behavior change. Local verification: `golangci-lint run -c
.golangci.yml` on the five affected packages reports 0 issues (the exact
CI gate); the targeted suites all pass — arrowbridge staging-text suite,
`pkg/sql/plan/function` TestUnsignedDecimalAdmission* +
TestCastDecimalExtremeExponentRendering, `disttae/cache`
TestColumnOnlyUpdateNeverDropsNumericAttributes, and `pkg/bootstrap`
TestCrossing*.

The same run's `UT Coverage on Ubuntu/x86` failure (job 123409393777)
and its downstream `Coverage` merge block are the known
`TestCrossTargetUpgradeRecovery` embedded-cluster admission flake
tracked in #31044 (comment below); the PR code does not execute in that
fixture-acquire failure.

### Base update (2026-10-29, merge commit 983cad4)

Main advanced with #31662 (`641c34d259`), which removed the periodic
`information_schema.COLUMNS/TABLES` repair walker and made the versioned
4.0.7 entry plus `CREATE ACCOUNT` initialization own convergence. That
removal conflicted with this PR's walker-ablation additions (which only
existed so upgrade scenario tests could attribute decoration to the
v4.0.18 entry). Merge `983cad4dc3` resolves it: the disable option,
gate, and struct field are dropped together with the ablation argument
at all 13 cluster-wiring call sites; with the walker gone, the scenario
tests' attribution premise holds unconditionally. This PR's v4.0.18
one-shot COLUMNS reconciliation entry is unchanged and is exactly the
supported convergence path on the new main.

Verification on the merged tree: `go vet` green on `pkg/bootstrap/...`,
`pkg/embed`, `pkg/frontend`; `golangci-lint` (repo config) reports 0
issues on `./pkg/bootstrap/...` and `./pkg/embed`; `pkg/bootstrap`
TestCrossing* and TestV407* pass;
`TestColumnsUpgradeAutomaticScenarioCompletion` passes as the
merged-premise end-to-end smoke.

The residual-risks note above mentioning the background walker "also
converges view text over time" is superseded: on current main the walker
no longer exists and the versioned entries own convergence.


### CI fix update #3 (2026-10-29, commit a15f2bf)

CI run 40880503711 at head 983cad4 (after the #31662 merge) failed
`UT Coverage on Ubuntu/x86` (job 123471690727):
`TestCreateAccountCatalogInitialization` in `pkg/tests/sqlintegration`
failed in 3.35s. That test was introduced by #31662 with a hard-coded
`create_version` expectation of `4.0.7`; this PR registers the v4_0_18
upgrade handle, so on the PR head `GetFinalVersion()` is `4.0.18` and
`CREATE ACCOUNT` stamps `mo_account.create_version = '4.0.18'` (bound to
`baseService.GetFinalVersion()` in `authenticate.go`). The stale literal
is updated to `4.0.18` in `a15f2bff2b`; the sibling scenario in
`collations_metadata_test.go` already compares against the dynamic
`upgrader.GetFinalVersion()` and passed in the same job. No
production-code change.


### CI fix update #4 (2026-10-30, commit 66bae00)

CI run 40902981503 at head a15f2bf failed `Matrixone Coverage
execution / Coverage` (job 123577267924): this PR's own diff coverage
measured 536/717 = 74.76%, below the 75% PR-coverage gate. The failure
is PR-caused (the gate only counts blocks this PR adds or modifies), so
the root cause is fixed with genuine test additions rather than any gate
change; nothing outside test files is touched:

- `pkg/sql/plan/function/func_cast_unsigned_decimal_test.go`:
admission-matrix coverage for the uncovered blocks in
`func_cast_unsigned_decimal.go` — signed fixed-width sources rejecting
negative rows (1264/22003) and pass-through for non-negative
float/int/uint/bool/bit rows; date/datetime/timestamp/enum decodes;
select-list row skipping across fixed, JSON, binary and varlena inputs;
binary decimal128/256 payload decoding and empty-payload errors; the
MySQL-prefix charset fast path; string outcome branches (pass through,
clip-to-zero with WARN_DATA_TRUNCATED + 1264 warnings under ignore
policy, and the fit-abstain path); varlena NULL rows; and the
nil-process out-of-range warning fallback.
- `pkg/container/arrowbridge/staging_text_test.go`: staged-text
rendering for the remaining Arrow scalar kinds (int8/16/32,
uint8/16/32/64, float16/32, decimal256), the rendered upper-bound table
for int/float/bool kinds plus its unsupported-source rejection, context
cancellation observed in both the whole-batch conversion and the
per-column staged loop, and row-budget rejection for unsupported staged
sources.
- `pkg/common/moerr/error_out_of_range_column_test.go` (new):
`NewOutOfRangeValueForColumnNoCtx` keeps the 1264/22003 wire contract
naming the column and 1-based row.
- `pkg/container/types/attributed_decimal_oid_test.go` (new):
`T.IsAttributedDecimalOid` accepts exactly the decimal family.

Local verification, reproducing the CI gate exactly: artifact profiles
from the failed run (UT + BVT pessimistic + BVT compose) merged by block
key with the profiles of these tests (same Go 1.27.1 toolchain), then
the CI `parse_coverage.py` rerun over this PR's diff: total 717 modified
blocks, covered 602, PR coverage 83.96% → pass (margin +9 points over
the gate). All named suites pass locally (arrowbridge staging-text file,
`pkg/sql/plan/function` TestUnsignedDecimalAdmission* +
TestAppendUnsignedDecimalOutOfRangeWarning*, moerr, types).

No production-code change; no CI/workflow change.


### Base update (2026-10-30, merge commit 8cc3ce9)

GitHub reported the PR CONFLICTING after main advanced with #31628 (FK
rebind to surviving keys, `969998e697`), #31738, #31746, #31766, #31767,
#31768, #31777. The only content conflict was
`pkg/sql/plan/build_ddl_test.go`: both sides appended independent test
functions after `TestSessionDatabaseNullability`. The resolution keeps
both — this PR's
`TestBuildCTASUnsignedDecimal{Attribute,SetOperation}Provenance` and
main's FK-rebind tests — with no changes to either test body.

All other shared files auto-merged on disjoint hunks, verified by
comparing both sides' diff regions against the merge base `641c34d259`:
`pkg/common/moerr/error{,_no_ctx}.go` (this PR's
`ErrOutOfRangeValueForColumn` 20211 vs main's `ErrDataBranchConflict`
22501, different code groups), `pkg/sql/plan/build_ddl.go` (this PR's
CTAS default/attribute region vs main's FK-rebind region), plus
`base_binder.go`, `build_alter_table.go`, `query_builder.go`, and
`pkg/vm/engine/disttae/txn_table.go`.

Local verification on the merged tree (Go toolchain, repo Makefile CGO
flags):

- `go build ./pkg/common/moerr/... ./pkg/sql/plan/...
./pkg/vm/engine/disttae/...` — green.
- `go test ./pkg/common/moerr/` — pass (covers both error-catalog
sides).
- `go test ./pkg/vm/engine/disttae/cache/ -run
TestColumnOnlyUpdateNeverDropsNumericAttributes` — pass (4 subtests).
- `go test ./pkg/sql/plan/ -run '<19-test seam regex>'` — all 19
top-level tests pass: this PR's 9 unsigned-decimal suites, main's 8
FK-rebind suites, `TestSessionDatabaseNullability`,
`TestBuildCTASPreservesMySQLSpecialColumnTypes`.

No production-code change in the resolution beyond the merge itself; no
CI/workflow change. Fresh CI on the new head was not awaited.


### CI fix update #5 (2026-10-30, commit 9d109f5)

CI run 40929677611 (attempt 1) at head 8cc3ce9 failed `Matrixone CI
execution / UT Test on Ubuntu/x86` (job 123645508612): package
`pkg/sql/plan/function` failed with `--- FAIL:
TestUnsignedDecimalAdmissionTemporalEnumAndUnsupportedSources` — `panic:
type mismatch: casting ENUM vector to []uint16` — and `CI Required`
failed as a consequence. The failure is PR-caused: the enum decode case
added in update #4 built its ENUM input vector through
`testutil.NewVector`, whose `T_enum` branch appends plain `uint16`;
`vector.AppendFixed[uint16]` trips the race-build
`checkTypeIfRaceDetectorEnabled` in `pkg/container/vector` (an
enum-typed vector is not type-compatible with `[]uint16`). UT runs with
`-race`, so the panic only fires there; local non-race runs passed,
which is how it escaped update #4. Production code is unaffected: the
admission path already reads enum vectors through
`unsignedDecimalAdmissionFixed[types.Enum]`.

Fix, test-only and one spot:

- `pkg/sql/plan/function/func_cast_unsigned_decimal_test.go`: construct
the enum source with `vector.NewVec(types.T_enum.ToType())` +
`vector.AppendFixed(types.Enum(7))`, the enum vector construction
already used elsewhere in the tree (e.g.
`pkg/sql/compile/fuzzyCheck_test.go`).

Local verification with the race detector (Go 1.27.1, repo Makefile CGO
flags):

- Before the fix: `go test -race -run
'^TestUnsignedDecimalAdmissionTemporalEnumAndUnsupportedSources$'
./pkg/sql/plan/function/ -count=1 -v` panics with the identical `type
mismatch: casting ENUM vector to []uint16` seen in the CI log.
- After the fix: the same command passes, and the full `go test -race
./pkg/sql/plan/function/ -count=1` — the package CI aborted early at the
panic — passes end to end.

No production-code change; no CI/workflow change. Fresh CI on the new
head was not awaited.


### Review fix update #1 (2026-10-30, commit 1a96756)

The local review at `9d109f531e` (CHANGES_REQUESTED) reproduced one P2
defect in `pkg/container/arrowbridge/staging_text.go`:
`renderedStageTextBound` estimated a staged Arrow decimal row as
`precision + 3` bytes, which only covers the fixed-point render form. A
declared scale outside the fixed-point domain renders the bounded
scientific form (`<coeff>e<-sf>`), whose exponent bytes the estimate
omitted, and a forged record can carry more coefficient digits than the
declared precision. `MaxOutputRows` then admitted a window of
individually valid rows whose rendered staging payload exceeded the
configured byte budget — the probe admitted two 10^37 rows at scale 1e9
under a 130-byte budget but materialized 148 bytes (146 at scale -1e9) —
leaving the reader's wire-size safeguard to split, copy, and discard the
excess rows.

Fix, scoped to the shared bound helper:

- `pkg/container/arrowbridge/staging_text.go`: `renderedStageTextBound`
now charges decimals the larger of the two reachable render forms over
the physical coefficient span — Decimal128 at most 39 digits (|2^127|),
Decimal256 at most 77 (|2^255|), signed two's-complement storage —
independent of the declared precision. Fixed-point needs a sign, the
digit run zero-padded to the gate-capped scale (<= 76), and the point;
scientific needs a sign, the digits, and `e` plus the
at-most-11-character negated int32-scale text. The resulting
conservative row bounds are 79 bytes (Decimal128) and 90 bytes
(Decimal256).

Regression coverage (`pkg/container/arrowbridge/staging_text_test.go`):

- `TestMaxOutputRowsAccountsScientificStagedText` (new, replicates the
review probe): plain and dictionary-encoded `DECIMAL128(38, +/-1e9)`
rows of coefficient 10^37 under a 130-byte budget admit exactly one row,
and the converted staging window materializes within the budget; a
two-row budget admits both with the encoding-independent 148/146-byte
footprints below the estimate.
- `TestRenderedStageDecimalBoundCoversWorstRenders` (new): the worst
renders the gate can physically emit reach the bound exactly (Decimal256
scientific at scale `math.MaxInt32` = 90 bytes; the shared renderer's
fixed-point ceiling = 79 bytes), and a forged 39-digit Decimal128
coefficient stays inside the bound.
- `TestRenderedStageTextBoundKinds`: pins the 79/90 decimal bounds,
including extreme declared scales;
`TestMaxOutputRowsAccountsRenderedStagedText` row arithmetic updated to
the new bound.

Local verification (Go 1.27.1, repo Makefile CGO flags): the new
regression tests fail on the pre-fix bound with the review's exact
symptom (budget admits 2 rows, expected 1; `arrow-staging-probe.log`
equivalent), and the full `go test ./pkg/container/arrowbridge/
-count=1` passes after the fix. `go test ./pkg/sql/colexec/external/
-count=1` passes except the pre-existing environmental
`TestExternalArrowLoadFromLocalMinIOAndRejectsObjectChange`, whose local
shared MinIO refuses writes because the host Data volume is at 100%
capacity ("minimum free drive threshold"). Production-code change is
confined to the row-size estimate rule; no CI/workflow change. Fresh CI
on the new head was not awaited.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants