Skip to content

Iscp alter table - #2

Closed
jiangxinmeng1 wants to merge 3 commits into
cpegeric:iscp_mergefrom
jiangxinmeng1:iscp_alter_table
Closed

jiangxinmeng1 wants to merge 3 commits into
cpegeric:iscp_mergefrom
jiangxinmeng1:iscp_alter_table

Conversation

@jiangxinmeng1

Copy link
Copy Markdown

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #

What this PR does / why we need it:

cpegeric added a commit that referenced this pull request Jul 21, 2026
… of 7)

Self-review (fulltext2_only vs cuvs_quantize, OOM focus) surfaced 7 defects; this
fixes 6:

#1 (BLOCKER, index.go) newBoundedTopK did make([]topKItem,0,k) — a pushed LIMIT
(clamped to MaxInt32) sized the phrase top-k to ~50GB and OOM-killed the CN on a
tiny table. Now: no pre-alloc (grow lazily to min(k,#matches)) + cap k to globalN in
SearchPhrase. Verified: MATCH ... LIMIT 500000000 on a 3-row table returns instantly.

#2 (BLOCKER, plugin/plan/tablefunc.go) fulltext2SearchColDefs declared
doc_id=T_int64/score=T_float64 but the executor AppendAny/AppendFixed[float32] — a
direct FROM fulltext2_search(...) wrote 4-byte floats into an 8-byte score column
(garbage ORDER BY) and mistyped non-int pks. Match the executor (T_any / T_float32),
same as the MATCH-path ftIndexColdefs.

#3 (index.go) ReconstructLiveDocs bucketed the WHOLE live corpus before yielding, so
MERGE (guard-exempt) peaked at O(corpus) Go heap — the reclaim op itself OOMs. A live
doc's postings are entirely within its own segment, so reconstruct ONE SEGMENT AT A
TIME: buckets is now bounded to O(one segment) (≤ capacity), freed before the next.

#4 (storage.go) checkTailLoadBudget gated on 1× SUM(LENGTH(data)) but load holds raw
chunks + reassembled frames + decoded segments at once; scale the estimate (×3) so the
guard fails before the real peak OOMs.

#6 (segment.go, termdict.go) loaded-side forEachPosting materialized the whole
vocabulary via prefixTerms("") ([]string); stream the FST via a new forEachTerm — no
O(vocabulary) spike compounding the MERGE peak.

#7 (serialize.go) decodeDocmap stored pk offsets in []int32; a >2GB docmap wrapped the
offset negative → pk(ord) panic. Fail fast at decode instead.

Deferred/decision-logged: #5 (stream.go:143 no-LIMIT non-disjunctive materializes all
matches) is partially mitigated by #1 (phrase pre-alloc now bounded to #matches); the
full fix is DAAT streaming for phrase/boolean (A2), bounded by the result set the user
asked for.

Verified: pkg/fulltext2 tests pass; live MERGE 25/25, fulltext2 37/37, membership
33/33, async 18/18; build/vet/gofmt clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
cpegeric added a commit that referenced this pull request Jul 24, 2026
…, base-load leak, plugin-kind)

#1 [P1] CDC last-write-wins (no frame reorder). A repeated upsert of one pk within
   an open tail segment merged old+new terms under one live doc, and an upsert to
   empty/NULL text left the old terms searchable. Add Builder.SetDoc(pk, words) which
   REPLACES a pk's terms (not append) and keeps a live 0-term doc for an empty upsert
   so it shadows older copies via recency; TailBuilder.AddBatch uses it (empty INSERT
   skipped, empty UPSERT shadows). Delete-first frame ordering is unchanged — UPDATE
   relies on it; the residual upsert->delete phantom is masked by the source-table join.
   Tests: SetDoc replace, upsert->upsert (no merge), nonempty->empty, nonempty->empty
   same flush, capacity-crossing, upsert->delete (documented), plain delete.

#2 [P1] cache coherence — DEFERRED to a follow-up PR (it is an all-index cache-layer
   change, not fulltext2-specific). Documented as an in-code Decision block on
   VectorIndexCache.Remove, with a pointer from the fulltext2 CDC consumer.

#3 [P1] DDL backup/restore round-trip. SHOW CREATE dropped position_free /
   max_index_capacity / max_postings_capacity, and checkpoint dump emitted classic
   FULLTEXT for a fulltext2 index (losing the engine). IndexParamsToStringList now
   renders position_free; SHOW CREATE fulltext2 emits the full option set; checkpoint
   renderCreateIndexStatement emits FULLTEXT2. Tests for the renderer + FULLTEXT2 round trip.

#4 [P2] partial base-load leak. LoadAllBases returned on a later LoadFromStorage error
   without freeing the already-mapped segments; now freeSegs(bases) first. Tests:
   freeSegs releases the mmap; LoadAllBases frees on partial failure.

#5 [P2] plugin index-kind contract. IsVectorIndexAlgo special-cased only classic
   fulltext by name, so a registered fulltext2 reported as a vector index. Add an
   explicit IsVectorIndex() capability to the catalog Hooks interface (vector plugins
   true, fulltext-family false); IsVectorIndexAlgo now delegates to it. Capability pinned
   in the fulltext2 + hnsw runtime tests.

Also: fix a space-before-tab whitespace lint in mysql_sql.y's mergeIndexOption block
(git diff --check clean; regenerated mysql_sql.go is byte-identical).

Perf follow-up (pooled phrase-buffer position retention; no-LIMIT phrase materializing
globalN) is tracked separately and not in this change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
cpegeric added a commit that referenced this pull request Aug 19, 2026
…sub-indexes

Two P1 blockers from the multi-sub-index rotation self-review:

P1 #1 — auto-rotation could commit an unqueryable IVF-PQ index.
    planCapacity splits a build into N sub-indexes when srcRowCount > rowsFit,
    each sized to fit 60% of build-time free VRAM. But at search time all N
    must be resident simultaneously (fan-out reads every sub-index per query).
    A table with ~2×rowsFit therefore built 2 sub-indexes, committed both,
    then OOM'd on the first query when the loader tried to hold ~120% of the
    build-time free VRAM. The build's silent success made the failure worse
    than the previous build-time OOM (which at least aborted loudly).

    Fix: pkg/vectorindex/loadadmit.go adds an AdmitLoadFits gate. Both
    CagraSearch.loadIndexes and IvfpqSearch.loadIndexes now sum idx.FileSize
    across the models being loaded and refuse before the first LoadIndex if
    the sum exceeds 60% of currently-free VRAM. The persisted tar size is a
    good proxy for the eagerly-resident footprint — it packages the raw
    dataset (CAGRA) / PQ codes (IVF-PQ), graph, ids, deleted bitset, and the
    per-INCLUDE-column filter_*.bin blobs written by FilterStore. Same 60%
    ratio as RowsFittingFreeMem so build and search bound consistently.

P1 #2 — hostRowsFittingMem used gopsutil/mem.VirtualMemory().
    On Linux gopsutil reads /proc/meminfo which reports host-wide memory,
    not this process's cgroup limit. A CN in a 64 GiB cgroup on a 512 GiB
    node would size against 512 GiB and be OOM-killed despite the claimed
    bound. Switch to system.MemoryAvailable() which the project already
    exposes cgroup-aware (both v1 and v2, with hierarchical minimum). Reword
    the unavail/unmeasured comment to match the new semantics: avail==0
    means unmeasured (bound skipped), avail>0 with rows==0 means measured
    but fits zero rows (caller must treat as hard error).

INCLUDE column bytes are NOT charged separately anywhere here — the
FileSize proxy already includes them (they land as filter_*.bin inside the
tar). No per-column bookkeeping needed.
cpegeric added a commit that referenced this pull request Sep 8, 2026
**CREATE-time schemas were not gated (P1 #1).** v4_0_7's
RequiredProtocolVersion only holds back widening tables that already exist.
CREATE INDEX is the other producer of a wide metadata table, and during a
rolling upgrade a new CN would create one that an old CN is still serving.
The old vector writers are POSITIONAL -- INSERT INTO meta VALUES (four
values) -- so they fail on arity against six columns, and a DEFAULT cannot
repair a value count. hnsw/cagra/ivfpq now build the legacy shape until
MOProtocolVersion reaches 57; fulltext2 stays wide because its writer
already named its columns.

The same CREATE-time widening broke the premise behind the CDC tail rows:
a wide table was proof that the gated migration had run and therefore no
un-upgraded reader was left. It no longer is, so emission asks the
deployment directly (ClusterHasIndexProvenance) in addition to the table
probe. An old CN reads the metadata table with SELECT * and would take
'cdc_tail:7' for a base sub-index and load it as one.

**Partial tail metadata was read as complete (P1 #2).** tailPeakBytes fell
back to the chunk count only when the frame-row sum was ZERO, so a tail
described in part was charged at the size of the described part. Two ways
in: a legacy tail migrated (columns added, no rows for frames already on
disk) then appended to, and a transient probe failure leaving a gap in the
middle. A 100 MiB tail plus a 1 MiB frame was charged as 1 MiB while
LoadTailSegments still loaded 101 MiB. The frame rows now report the chunks
their bytes occupy, and every chunk no row covers is bounded by the cap it
was written under.

**Reservation publication was not linearized (P1 #3).** seq was taken with
Add(1) and published later with Store; pendingAhead ignores higher seq. So
A could take seq=1 and stall, B take seq=2 and pass as sole occupant, then
A publish and pass too -- both seated against one budget. Taking the number
and publishing it are now one step, which makes a later number prove every
earlier one is visible. Separately, pending is now read BEFORE residents: a
load that becomes resident and then drops its reservation between the two
reads was missed by both, and is now counted twice instead, which only
refuses too early.

Also fixes a nil dereference the gates would have hit: ServiceRuntime
returns nil for a service it has never seen.

Design doc gains sections 12-14. Tests: the mixed-version CREATE matrix,
withheld-then-emitted tail rows, legacy-tail/missing-middle-frame sizing
with covered and empty controls, and an ordering control for reserve that
fails without the fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_011Nq7vTpoSjbxcP2WhDKrJC
cpegeric added a commit that referenced this pull request Sep 10, 2026
Two fixes to the json_extract coverage gate:

#2 cross-account snapshot: decideJSONProbe ran its freshness reads (source
relation, ISCP log, index metadata) under the READER's account, so a
{snapshot=...} read of another account's data declined to a full scan (wrong
account -> table-not-found / empty). It now binds the snapshot's owning tenant
(from ApplyScanSnapshot's resolved account) onto the context for those reads,
mirroring what the base-table scan already does. No-op for an ordinary
current/same-account read.

#3 bounded SourceCommitTS: the coverage bar is only ever compared against the
index build_ts, so the exact source-commit maximum is unnecessary. SourceCommitTS
now takes a mustExceed hint (the build_ts) and returns as soon as the terms
gathered so far exceed it -- checked before each object's disk I/O, so a recent
in-memory row or the retention-boundary floor settles "behind" with zero object
reads. An empty mustExceed disables the short-circuit (exact maximum) for any
other caller. The bar is also computed lazily via a Request callback and only
when build_ts is a live, non-empty value it could gate, so a not-built or
not-live index skips the scan entirely.

Tests: partition-state short-circuit skips an un-loadable object (proving no
I/O) + retention-floor early-out; cross-account binding asserts the snapshot
tenant reaches GetRelationById; coverage-gate callback contract; all existing
source-commit-ts/coverage/decide-matrix suites updated and green. Full
json-probe BVT suite 154/154.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
cpegeric added a commit that referenced this pull request Oct 6, 2026
…atrixorigin#29496)

Address XuPeng-SH's review of the amended v3 contract.

P2 #1 (code) -- the build-time scalar fallback could return NaN into ranking.
The *Unrolled oracles are 8-wide unrolled, not strictly sequential, so a block of
same-sign extreme-but-finite products overflows to +/-Inf and two opposite-sign
blocks cancel to NaN -- the same artifact as the SIMD lanes, at block width. The
non-SIMD wrappers (distance_func.go, selected when GOEXPERIMENT is unset) returned
that NaN raw, unlike the SIMD recover* and the narrow scalar kernels. Witness
(f32, dim64): query all 2^63; cand0 = 2^63 at 0..7, -2^63 at 32..39; cands
[1,0,...] and [2,0,...]; top-2 returned [2,0] with a NaN distance instead of the
finite [2,1].

Fix: bake the no-NaN finalizer into each ranking-distance oracle at its own return
(matching innerProductBF16 / cosineDistClamped): InnerProductUnrolled ->
nanToPosInf(-sum); CosineDistanceUnrolled -> cosineDistClamped (dropping its
duplicate manual clamp); SphericalDistanceUnrolled -> nanToPosInf. CosineSimilarity
is untouched (not a ranking metric; its only consumer is the boundary-checked
moarray builtin, and +Inf is wrong-direction for a similarity). The non-SIMD
wrappers need no change; the SIMD recover* outer nanToPosInf is now redundant and
simplified away.

Tests: a build-independent oracle test asserts the three oracles never return NaN
on the block witness, and a non-SIMD-build brute-force test reproduces the
reviewer's selection witness ([2,1], not a NaN winner). Both builds green.

P2 #2 and P3 (design doc) -- narrow the cross-mode equivalence claim to exclude a
genuine overflow a SIMD tier cancels across lanes to a finite (wrong) value, which
the result-only recovery predicate cannot see (explicit domain limit, no precheck
or widening); correct the first-bullet "sequential scalar sum stays finite"
over-simplification (the oracle is unrolled); and replace the unsupported ~2x
exceptional-path bound with bounded O(d) plus representative measurements.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
XuPeng-SH pushed a commit that referenced this pull request Oct 28, 2026
…ternal tables; rework query-result dump-format lifecycle (matrixorigin#30570 matrixorigin#31261) (matrixorigin#31466)

matrixorigin#30570: `MODUMP QUERY_RESULT '<query-id>' INTO '<path>'` always wrote CSV regardless of the
output file's extension, because `doDumpQueryResult` (`pkg/frontend/query_result.go`) never set
`ExportParam.ExportFormat` and never called the format validation — the suffix-driven logic
(`inferFormatFromSuffix` / `validateExportFormat` in `pkg/frontend/export.go`) was only wired
into the `SELECT ... INTO` / `EXPORT` path. The MODUMP path now calls `validateExportFormat`
before writing, so `.jsonl`/`.jsonline`/`.ndjson` produce JSON Lines and `.parquet` produces
Parquet through the existing shared `ExportConfig` write path (init → openNewFile → per-block
write → finish). Unit tests verify the dumped bytes with a real Parquet reader readback
(`TestDoDumpQueryResultHonorsFileSuffix`) and invalid-UTF8 JSON Lines rejection
(`TestDoDumpQueryResultJsonlineRejectsInvalidUTF8`). The new BVT case
`modump_query_result_error_reuse` additionally verifies that MODUMP against an unknown query id
returns a deterministic error and the same connection stays usable for the next statement —
that is failure-path regression *verification*, not the issue's original symptom.

matrixorigin#31261: SHOW CREATE TABLE for ordinary (non-Hive, file-based) external tables emitted
`INFILE{'FILEPATH'=''}` — the FILEPATH was dropped from the generated DDL, so a replayed
or restored DDL pointed at nothing and the recreated table was unreadable.
`buildShowCreateTable` now keeps the original FILEPATH in the INFILE clause (S3
credentials stay masked); the emitted DDL is re-executable as-is for ordinary server-local paths, while credential-bearing service-argument paths are intentionally redacted (`<redacted>`) and the owner must re-supply credentials before the replayed table is usable.

Review follow-up on matrixorigin#31261 (this head): the retained FILEPATH can itself embed
fileservice service-argument credentials (`'FILEPATH'='s3-opts,endpoint=...,key=K,
secret=S:rows.csv'` or positional `s3,endpoint,region,bucket,key,secret:file`), which would
leak object-store secrets into schema dumps — violating the no-secrets requirement. This head
adds `maskServiceArgumentCredentialsForShowCreate` (`pkg/sql/plan/build_show_util.go`), applied
to both the INFILE branch and the explicit-S3 branch's `'filepath'` option. It decodes the
service section with the production `parseService` rules (comma split / `csv.ReadAll`, service
separator at the LAST colon), redacts k=v credential keys (`key`, `key-id`, `secret`,
`key-secret`, `secret-id`, `bearer-token`, `security-token`, `token`, `session-token`,
`kerberos-password`; case-insensitive) for `s3-opts|opts|options|hdfs`, and redacts positional
key/secret at argv index 4/5 for `s3`/`minio` (mirroring `fileservice/get.go`
`parseFileServiceArguments`). Ordinary server-local paths (`/data/...`, `stage://...` claims
untouched unless credential-service-claimed) round-trip byte-for-byte, preserving the matrixorigin#31261
replay contract. Because CREATE admission (`InitInfileParam`) validates only option keys and
never parses the path grammar, malformed-but-credential-bearing forms *are reachable* in stored
metadata, so the renderer fails closed for: CSV-grammar errors on a credential-claimed section,
short-but-credential-bearing positional forms (5-field `s3,ep,region,bucket,KEY:file` leaks
argv[4] and is redacted), colonless `s3-opts,key=...,secret=...` claims, and the
`EncodeServiceCSV` error fallback (practically unreachable; fail-closed anyway). Valid
non-credential positions (positional prefix/name at index 6/7, `s3,ep:` credential-free short
form, unknown services, `role-arn`/`external-id`) are preserved verbatim.

Validation (raw rcs kept in the review session; evidence recorded):
- Review-fix unit + production-arc tests (`pkg/sql/plan/build_show_util_external_replay_test.go`):
direct masker table cases plus a real CREATE planner → `SystemRelAttr_CreateSQL` stored
property → `ConstructCreateTableSQL` consumer arc proving synthetic secrets never reach
dump-visible SHOW CREATE output while local paths stay byte-exact; malformed quoted
service sections, short positional forms, colonless claims, and the explicit-S3 branch
credential-qualified filepath are covered, together with the review witnesses
`"s3-opts",key=K,"secret=S:rows.csv` and `"s3-opts",key=K,secret=S` (fully-quoted and
colonless claims, fail-closed) and quoted-local-path negative controls preserved verbatim.
Focused CGO at current head `512d744e8656fe088a2c2938e96d126840956ed9` (command:
`GOWORK=off CGO_ENABLED=1 .agents/skills/mo-dev/scripts/mo-cgo-test -count=1
-timeout=600s -run 'TestFormatInfileExternalOptionsMasksServiceArgumentCredentials|TestShowCreateCreatePlannerExternalTableMasksServiceArgumentCredentials|TestShowCreateExternalMasksFailClosedAndS3BranchFilepath|TestGetMaskTypeExternal|TestConstructCreateTableSQLOpositionExternalOptions|TestInfileExport' -v ./pkg/sql/plan/...`):
rc=0 — 3 top-level tests matched, 25 PASS (3 top-level + 22 subtests) / 0 FAIL; the other
3 named patterns matched no tests and 18 other listed packages printed `[no tests to run]`.
Scoped static at current head: repo target `static-check-selected` with
`STATIC_CHECK_PACKAGES=./pkg/sql/plan/...` (molint + go vet + golangci-lint): rc=0,
`0 issues.`. Not claimed: a whole-package `./pkg/sql/plan` run, live S3, or a live mo-dump
of the redacted output (assertions are on the exact rendered string that mo-dump captures);
prior "6 top-level tests, 7 PASS" evidence belongs to the superseded head and does not
carry to this head.
- Feature evidence from earlier rounds is unchanged: `external_table_show_create_replay`
BVT static oracle + second-root rerun; hardened SHOW CREATE oracle reruns
(`alter_table_add_drop_primary_key` 265/265, `alter_table_rename_column` 270/270,
`show_create_table` 64/64, `external_table_error_mode` 45/45, replay 13/13) under an active
dispatcher port guard (23000-23999, HAKeeper 127.0.0.1:23401, owned-PID cleanup);
negative-control mutation (rc=1) proving the oracle is live; the matrixorigin#31261 isolated-cluster
mo-dump → native mysql restore → identical rowset chain; `stage_based_stage` row-order fix
(307/307, that case only). `e2e-postrebase.log` is reported with its older local base (533e957)
and is not an artifact of the final HEAD binary.

Source identity and delivery fence:
- Current head `512d744e8656fe088a2c2938e96d126840956ed9` = feature commit
`2ce641877f` on upstream main `1fd12d526e` + review-fix #1 `170195b9fa`
(masker redaction, rebased) + review-fix #2 `512d744e86` (fully-quoted and
colonless service-argument fail-close); linear rebases only, never merged.
Complete diff versus base `1fd12d526e` is 22 files (+1023/-43), sha256
`a1d54634b269869f1ff340411e916f96a27c5ac81e65a2b303327599a8d828bd`;
delivery-accepted fingerprint, remote readback identical. Superseded head
`be4a044e5d438f70af61ebd69528117f81081dbe` (feature on `c4946bb74d` +
review-fix #1) had complete-diff sha256
`62af31284425a29b942ee97bf70ca939574a6746e7195a31c4001e3c4bde9fcb`; older
superseded head `9033069e3d` was the pre-review-fix feature head against
`d4ffbae4` (parent `d4ffbae43d55da21526eab01722cbef14bb01ed5`), rebased onto
`3b7752551b` as `cda8df8d0e` before any review fix.
- Known limitations (masked display only): unknown service names are not masked (production
admits no other credential-bearing service than the listed set); arbitrary data in
non-credential fields is not masked; the stored catalog metadata retains the original
credentials (as designed for restore access) — only rendered SHOW CREATE / dump text is
redacted.

Port-guard boundary: one consolidation service run during local verification fell inside a
brief port-guard rebind window and lacked a complete owned-socket audit; no claim is made
about that window. Only the subsequent fully-audited, guard-on reruns are asserted as
service evidence above.

Known-risk notes: the change is additive in SHOW CREATE text (FILEPATH now present for
file external tables, credential-bearing service arguments redacted) and adds one validation
call on the MODUMP path; no on-disk format, catalog metadata, or wire-protocol change.

Approved by: @XuPeng-SH
cpegeric pushed a commit that referenced this pull request Oct 28, 2026
…atrixorigin#31524)

The escaping parts of matrixorigin#31384 are already fixed on `main` (matrixorigin#31262 for `metadata_scan` and matrixorigin#31322 for `_build_moctl_sql`; see the issue comment). This PR fixes what is left: expected behavior #2, a non-JSON `mo_ctl` reply.

**Root cause.**
1. `_execute_moctl` (sync in `moctl.py`, async in `async_client.py`) called `json.loads(result_str)` directly. On a plain-text reply it raised `MoCtlError("Failed to parse mo_ctl result: Expecting value: line 1 column 1 (char 0)")`, and the server's actual output was lost.
2. A `MoCtlError` raised inside the `try` block (no rows, or a `returnStr` other than `OK`) was caught again by `except Exception` and re-wrapped, so the message read `mo_ctl operation failed: mo_ctl operation failed: table not found`. In the async manager the same re-wrap also hid the JSON error behind the generic prefix.

**Fix.**
- New `_decode_moctl_result()` in `moctl.py`, shared by both managers. On non-JSON it raises the manager's own `MoCtlError` class: the sync manager uses `matrixone.moctl.MoCtlError` and the async manager uses `matrixone.exceptions.MoCtlError`, as before.
- The error message includes a raw-output preview (capped at 500 chars). The full text is available as `error.raw_output`.
- `except MoCtlError: raise` lets SDK errors pass through unwrapped. Other exceptions are still wrapped as before.

**Tests** (`tests/offline/test_moctl.py`):
- `test_execute_moctl_non_json_keeps_raw_output`: a sync plain-text reply keeps the raw text in the message and in `raw_output`.
- `test_async_execute_moctl_non_json_keeps_raw_output`: the same check for the async manager.
- `test_execute_moctl_failed_return_str_is_not_double_wrapped`: the message is exactly `mo_ctl operation failed: table not found`.

**Results:**
- Before the fix, all 3 new tests fail (the actual message was `mo_ctl operation failed: mo_ctl operation failed: table not found`). After the fix, all 3 pass.
- `test_moctl.py` + `test_moctl_simple.py`: 26 passed.
- `pytest tests/offline` (Python 3.13, run locally): 2289 passed, 95 subtests passed.
- `black --check` is clean. `flake8` reports no new warnings (4 before, 4 after; all are existing unused imports in `async_client.py`).

3 files, +61/-9.

本操作由 LW 授权的 Grok Bot 智能体执行

Approved by: @XuPeng-SH
cpegeric pushed a commit that referenced this pull request Oct 30, 2026
…matrixorigin#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 matrixorigin#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 matrixorigin#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 matrixorigin#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 matrixorigin#31662 merge) failed
`UT Coverage on Ubuntu/x86` (job 123471690727):
`TestCreateAccountCatalogInitialization` in `pkg/tests/sqlintegration`
failed in 3.35s. That test was introduced by matrixorigin#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 matrixorigin#31628 (FK
rebind to surviving keys, `969998e697`), matrixorigin#31738, matrixorigin#31746, matrixorigin#31766, matrixorigin#31767,
matrixorigin#31768, matrixorigin#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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant