Skip to content

Commit 8197e28

Browse files
fix(sysview): publish declared COLUMNS metadata, numeric SUB_PART and full generated expressions (#31489)
## 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 #30936. Related to #30935. Related to #30937. ## What this PR does / why we need it: Fixes the declared-catalog metadata defects of #30936/#30935/#30937 and delivers the corrected identities through the repository's supported model: **unconditional publication plus one idempotent stored-view refresh hop**. No feature-specific protocol gate and no mixed-version fallback exists in this PR: after the first implementation review every such mechanism was removed (`MORPCLatestVersion` stays 134, no read substitution, no admission survey, no per-tenant floor), while the stored-view migration the reviewers called "necessary" is retained. ### Design record (design-first review chain) The change is triggered (persisted-view migration, upgrade recovery, cross-subsystem changes), so the repository's design gate applies: `docs/design/20261026-declared-catalog-metadata-publication-and-repair.md` is the reviewed artifact, implementation of each round proceeded only after that round's independent design review returned PASS, and the document's status block and revision history record every reviewed revision's exact content hash, disposition and implementing head: - Revision 9 (sha256 `57043aac71c74a7cb63f0a8ac047a4ac898bf974791644569e5c57f4bd2838d9`), PASS 2026-10-28 - the shutdown-only rework that removed the protocol-135 gate family; implemented at rework head `9f454cb5d0`. - Revision 12 (sha256 `47ebfe15a45940221c3d2d5ad6955e11a5c89a1a909fa9d4e382e1ac9db0a599`), PASS 2026-10-29 - the post-consolidation vehicle plus preserved upgrade admission and on-demand continuation; implemented at head `efb7234682`. - Revision 14 (sha256 `22aaf464a18a8be7e7d4889e605850c0792bca6df7bd234e97569445b0c84c66`), PASS 2026-10-30 - the rebase onto upstream #31739's ladder: vehicle renumbered to `v4_0_19`, the merged COLUMNS identity, the frozen 4.0.18-snapshot recognition, the direct-route census. This is the delivered design content; it was implemented at head `61da7f8ef0`. - The design-first decision of record for revision 14 is identified and linked in the tracked document (revision 16) and here. The returning review was the controller-run independent pre-PR design review: a read-only, ephemeral Codex review session under the `fix-issue-loop-local-reviewer` contract, provider-separated from the implementing Grok CLI session (reviewer model `gpt-6.1-sol`, reasoning effort `xhigh`; implementing handler `magpie/tass/glm-5.3`; controller run `3dedc8b010734de9ba6a4c92c3fdf56e`, review session thread `01a18bcc-5369-7d91-ae66-c072a48a5b1e`, run window 2026-10-30T07:53:04Z-07:59:46Z, exit 0). It returned `approved: true` (PASS - design only, no findings) at 2026-10-30T07:59:46Z for exactly that content hash. Retained external evidence: the approved bytes are public at https://github.com/matrixorigin/matrixone/blob/61da7f8ef005f2ee14a3ea44e738e6baee24876d/docs/design/20261026-declared-catalog-metadata-publication-and-repair.md (that committed document hashes to the approved sha256); the verbatim decision record plus its provenance is durably published at https://gist.github.com/gouhongshen/f1120ed42e7a71f75afa79d1ff8b5bc2; and the controller retains the full review transcript and the exact checkpoint submission the reviewer was sent (`state/logs/issue-30936/1793346784-b0837235.jsonl`, `state/artifacts/issue-30936/pr-event-result-1793345798133.json`), next to every earlier round's decision record under `state/artifacts/issue-30936/` (revision 9 PASS `pre-pr-review-1793174134562.json`, revision 10 REQUEST_CHANGES `pre-pr-review-1793224739314.json`, revision 11 REQUEST_CHANGES `pre-pr-review-1793225484685.json`, revision 12 PASS `pre-pr-review-1793226200902.json`, revision 13 REQUEST_CHANGES `pre-pr-review-1793323124836.json`). - Revision 15 (sha256 `551fb06436f784e8b75fa9c7d37702ea47379ed5902256b8188d1dfcacb22f6c`) - the documentation-only consolidation at the implementation review's request (head `38901ce0e7`): the design-approval chain and the actual `v4_0_19` vehicle are stated in the document's status block, the revision-13/14 amendments are folded into the standing sections, and the transient review/run correspondence was moved out of the tracked file (it remains recorded in the review threads and retained review evidence). No decision, invariant, oracle or validation entry changed from the approved revision 14; the approved revision-14 wording governs wherever the consolidation could be read as a change. - Revision 16 (sha256 `2df7a7dfef372bf41feb160c3c3252ac9f1d6b3522106c94fe1e3f5d038d9f8d`) - the documentation-only evidence-link pass at the design-gate review's request (this push): the tracked design's status block and revision history now identify the actual design-first decision of record for the delivered revision and its reviewer, and link the retained external evidence (public byte link of the approved content, durable verbatim decision-record gist, controller-retained transcript and checkpoint submission). No decision, invariant, oracle or validation entry changed from the approved revision 14. ### Delivered vehicle The stored-view refresh hop is `pkg/bootstrap/versions/v4_0_19` - version "4.0.19", minimum upgrade version "4.0.7", required protocol 118 (a pre-existing grandfathered gate), offset 2 - registered on main's consolidated ladder behind upstream's `v4_0_18` handle (upstream #31739 consumed the planned successor slot as "4.0.18", so the vehicle was renumbered after it). Its tenant hop publishes both identities for existing accounts: a ready 4.0.7 cluster queues the single direct [4.0.7 -> 4.0.19] upgrade executed by this handler alone, a main-era 4.0.18 stamp queues the direct [4.0.18 -> 4.0.19] upgrade, older sources chain their per-handle rows through the frozen 4.0.7 stage and the 4.0.18 handle, and the login/manual on-demand walks step every successor handle (upstream's re-entrant planning loops with this PR's manual-walk completion check); fresh accounts initialize at 4.0.19 with the published identities and run no leg. ### Root causes 1. `information_schema.COLUMNS` (#30936) derived every declared-metadata field from the physical column type alone: `internal_char_length(mc.atttyp)` and `internal_numeric_precision(mc.atttyp)`. ENUM is stored as an internal uint16 and SET as a uint64 bitmap, so both published SQL NULL for `CHARACTER_MAXIMUM_LENGTH`/ `CHARACTER_OCTET_LENGTH`, while SET exposed its backing-store `NUMERIC_PRECISION=20`/ `NUMERIC_SCALE=0`. The declared labels persisted in `mo_columns.attr_enum` were never consulted. 2. `information_schema.STATISTICS` and `SHOW INDEX` (#30935) published NULL literals and the string `'NULL'` for `SUB_PART`/`Sub_part`, although prefix lengths are retained in `mo_catalog.mo_indexes.algo_params`. 3. `GENERATION_EXPRESSION` (#30937) went through `varchar(500)` casts, silently truncating declared generated-column expressions longer than 500 characters. ### Exact changes (shutdown-only delivery) - `pkg/sql/plan/function`: additive two-argument overloads (`varchar,varchar -> int64`) on `internal_char_length`/`internal_char_size`/ `internal_numeric_precision`/`internal_numeric_scale` that derive character metadata from the declared ENUM/SET labels and suppress SET's bitmap numeric identity, plus the new `mo_index_sub_part` function. The historical one-argument overloads remain bound for definitions persisted by older binaries; the new ones carry **no protocol requirement**. - `pkg/util/sysview`: the current `COLUMNS` identity composes those label-aware overloads and the unbounded `GENERATION_EXPRESSION` projection on the `#31160` binary-family NULL selector, under upstream #31739's attributed-DECIMAL `COLUMN_TYPE` decoration applied verbatim (`COLUMN_TYPE` pinned to `varchar(65535)`, `att_is_unsigned` decked ancient rows - D13-2/D14-1); the current `STATISTICS` identity publishes retained prefix lengths as a numeric `SUB_PART` (actual SQL NULL for whole-column parts). Bootstrap init, CREATE ACCOUNT and subscription publication install these identities unconditionally: after main's #31662, CREATE ACCOUNT installs the complete current definition set or aborts, so this PR adds no rung, survey or authoring floor. - Historical-snapshot reader recognition (invariant I6): the snapshot adapter `AdaptLegacyInformationSchemaColumnsDDL`, the derived view-metadata seam `ViewMetadataColumnsDDL` and the migration gate `IsInformationSchemaColumnsMigrationDDL` recognize every recent published generation byte-stably - the historical templates, the base-era NULL-selector MEDIUMINT identity, and the exact upstream 4.0.18 published identity frozen independently of the mutable current constructor (`InformationSchemaColumns4018DDL`, D14-1) - next to the corrected current. Unknown or user-edited definitions stay refused with the unchanged error, `IsCurrentInformationSchemaColumnsDDL` stays exclusive, and snapshots keep their recorded projections and timestamp; the readers stay read-only. - `pkg/bootstrap/versions`: the `v4_0_19` tenant hop carries the two shared-builder legs: the shared COLUMNS entry keeps its exact base shape (`UpgSql = sysview.InformationSchemaColumnsDDL`, protocol gate 109, exact-identity CheckFunc, DROP+CREATE), so refreshing an account installs the merged identity; the shared STATISTICS entry publishes the prefix-aware identity under the pre-existing STATISTICS gate (41). One idempotent rewrite per pre-existing account; completed legs never churn; a failed leg leaves the account marker untouched and retries. - `pkg/bootstrap` upgrade admission and continuation: upstream's re-keyed admission guards (the `>= 4.0.7` line, the registered frozen-handle identity and the `crossingPending` route predicates) are adopted verbatim; this PR keeps the recovery-path guards (the frozen 4.0.7 target's legacy-CDC admission and the offset-only resume rejection) that a final above 4.0.7 otherwise bypasses, and adds the manual walk's in-transaction completion check (an account left below the cluster final returns `cannot upgrade tenant version %s to current cn version %s` instead of caching success) - upstream's loops alone lack it. - `pkg/sql/plan`: `SHOW INDEX` publishes `Sub_part` through `mo_index_sub_part` (numeric protocol type, actual SQL NULL without a retained prefix). - `MO_INDEX_SUB_PART` is id 623 (`FUNCTION_END_NUMBER` 624) after upstream #31739 allocated 620..622 for the unsigned-Decimal admission checks; the id is internal plan wiring only and every view DDL references the name. - **Deleted with their suites** (the withdrawn mixed-version machinery): the `MORPCVersion135` constant and plan feature flag, the persisted-expression/remote-execution protocol mappings for it, the admission/authoring-floor branches in tenant publication, the `FrozenViewServingBelowMetadataFloor` read substitution and its serving-floor adapter, the metadata maintenance pass and its restore-compatibility/admission-interval tests. The pre-existing 118/126 admission handoffs, the VIEWS authoring fence, the 130-134 upstream planes and the columns/tables maintenance keep their base behavior untouched. ### Issue-to-test proof Defect oracles (unchanged red/green pair on base `7e0c9d94` vs the fixed tree; recorded probe logs and full-suite receipts in the review evidence): - #30936 (`pkg/tests/issues/issue_30936_test.go`, `issue_30936b_test.go`, `pkg/sql/plan/function/func_internal_columns_metadata_test.go`): for `t(id INT PRIMARY KEY, e ENUM('a','bb'), s SET('a','bb'))` the base returned SQL NULL character lengths and SET numeric 20/0; the fixed tree reports `e` 2/8 and `s` 4/16 with SQL NULL numeric metadata, on both CNs, for reordered and multibyte label sets (`1/3`, `2/4`), with the INT control at 10/0; empty-domain and colliding-declaration boundary batteries pin the `attr_enum` encoding boundary. - #30935 (`func_internal_index_sub_part_test.go` plus the issue SQL): `SUB_PART`/`Sub_part` report the declared prefix length (numeric `LONGLONG` at the client) and actual SQL NULL for whole-column positions on both surfaces. - #30937: full declared expressions of 499/500/501/646/800 characters round-trip through `GENERATION_EXPRESSION`, `SHOW CREATE TABLE` and the evaluated values, VIRTUAL and STORED. Delivery and history oracles (all green at the delivered head): - Publication (`pkg/frontend`, `pkg/util/sysview`) : `TestCreateTablesInformationSchemaPublishesDeclaredMetadataUnconditionally` proves fresh creation executes the corrected declared-label COLUMNS identity and the prefix-aware STATISTICS identity and never authors a predecessor identity, beside upstream's own `TestCreateTenantInformationSchemaRequiresCurrentProtocol` peer-answer rejection matrix. - Hop (`pkg/bootstrap`): rewrite/no-op/retry chains for the v4_0_19 hop - base-era NULL-selector and V110 tenants converge to exactly the published identities, a current tenant is a no-op, a mid-hop DDL failure leaves the marker untouched and repairs on retry, and a 4.0.13 account converges through the whole historical chain (`TestColumnsUpgradeReachesExistingTenants`; the maintenance keeps a single current identity across shared/maintenance/hop). - Upgrade admission and recovery (admission oracles re-derived at the three-handle registration, final 4.0.19): the ready 4.0.6, created-4.0.7, off-frozen-offset and interrupted offset-only routes keep upstream's terminal rejections (`TestLegacyCDCAdmissionBeforeUpgradeMutation`, `TestV407RejectsDifferentOffsetBeforeCreatingRoute`, `TestV407RejectsInterruptedOffsetOnlyRouteBeforeMutation`) including the recovery path, with the crossed-route non-rejection the pending-scan permits; the continuation oracles drive the real `v4_0_7` handler plus the successor registration (late-login convergence from 4.0.6 to the final, already-4.0.7 manual upgrade, failure/retry without premature caching, second-login idempotence and the no-successor-SQL-before-4.0.7-completion ordering). - Historical transition H1a/H1b (design section 7): the base-era pair and the frozen `InformationSchemaColumns4018DDL` identity are recognized byte-stably at all three reader seams, an unknown definition stays refused at every seam, and with the live view at the corrected identity a snapshot recorded at the base-era or the 4.0.18 current definition binds and returns its recorded text with its projections and timestamp preserved, while the pre-refresh leg pins a live 4.0.18 definition still gating legacy adaptation (no silent pass-through). - Version-census oracles: route fixtures carry the composed route matrix (the single direct [4.0.7 -> 4.0.19] row, the direct [4.0.18 -> 4.0.19] row, three-leg chained census for below-4.0.7 sources, the frozen-4.0.7 resume admission), and `pkg/tests/sqlintegration/TestCreateAccountCatalogInitialization` and `pkg/embed/catalog_view_identity_test.go` derive their expected version from the registered final (`GetFinalVersion`), so renumbered vehicles no longer retire a version literal one by one. ### Verification at the delivered head (repository CGo wrapper, real exit statuses in the round logs) All green at the reworked head `61da7f8ef0`: the full `./pkg/bootstrap/...` ladder (route/continuation/recovery/census, including the renamed vehicle's own `versions/v4_0_19` suite and upstream's `versions/v4_0_18` suite), the full `./pkg/util/sysview`, `TestHistoricalViewColumnsSQL` in `pkg/sql/plan`, the full `./pkg/sql/plan/function`, `TestIssue30936*` in `./pkg/tests/issues` replaying the three issue reproductions, `TestCreateAccountCatalogInitialization|TestCollationsMetadataUpgrade` in `./pkg/tests/sqlintegration`, the `pkg/embed` catalog identity pair + caller-owned continuation oracle, and the `pkg/frontend` publication oracle pair. The first full bootstrap pass at this head also exposed that upstream's crossing-admission fixtures still modeled the upstream-only route matrix; they were re-derived to this delivery's composed census (per design D13-7/D14-3, no production change) and the focused rerun and full ladder rerun are green - the first-pass failure is retained verbatim in the round logs as the fixture-round evidence. Earlier rounds' receipts remain valid for the unchanged parts per the repository's evidence-reuse rules; the distributed multi-CN BVT and hosted CI matrix remain CI work at the pushed head. ### Residual risks - Main advanced during the ladder runs (`mergeStateStatus: BEHIND`), with no file-level overlap against this PR's 37 files; freshness is left to the merge queue rather than a rebase. - ENUM/SET declarations whose labels explicitly contain a comma remain split-interpreted end to end (metadata, `SHOW CREATE TABLE` and accepted values). This is the pre-existing `attr_enum` comma-join catalog encoding (unchanged base behavior); the boundary is documented in the design note (sections 2.3/4.3/8), pinned by `TestInternalDeclaredLabelEncodingBoundaryOracle` and `TestIssue30936DeclaredLabelEncodingBoundary`, and scheduled as a separate gated catalog-format follow-up. - Convergence is framework-timed by design: until a given pre-existing account's hop leg completes, that account keeps serving its pre-correction (readable) values - the same convergence timing every version-held correction has. --------- Co-authored-by: XuPeng-SH <[email protected]>
1 parent d159489 commit 8197e28

37 files changed

Lines changed: 4926 additions & 105 deletions

‎docs/design/20261026-declared-catalog-metadata-publication-and-repair.md‎

Lines changed: 2176 additions & 0 deletions
Large diffs are not rendered by default.

‎pkg/bootstrap/columns_upgrade_test.go‎

Lines changed: 191 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// you may not use this file except in compliance with the License.
55
// You may obtain a copy of the License at
66
//
7-
// http://www.apache.org/licenses/LICENSE-2.0
7+
// http://www.apache.org/licenses/LICENSE-2.0
88
//
99
// Unless required by applicable law or agreed to in writing, software
1010
// distributed under the License is distributed on an "AS IS" BASIS,
@@ -16,17 +16,22 @@ package bootstrap
1616

1717
import (
1818
"errors"
19+
"fmt"
1920
"strings"
2021
"testing"
2122

2223
"github.com/golang/mock/gomock"
2324
"github.com/matrixorigin/matrixone/pkg/bootstrap/versions"
25+
"github.com/matrixorigin/matrixone/pkg/bootstrap/versions/v4_0_18"
26+
"github.com/matrixorigin/matrixone/pkg/bootstrap/versions/v4_0_7"
2427
"github.com/matrixorigin/matrixone/pkg/common/moerr"
2528
"github.com/matrixorigin/matrixone/pkg/common/mpool"
2629
"github.com/matrixorigin/matrixone/pkg/common/runtime"
2730
"github.com/matrixorigin/matrixone/pkg/container/types"
31+
"github.com/matrixorigin/matrixone/pkg/defines"
2832
mock_frontend "github.com/matrixorigin/matrixone/pkg/frontend/test"
2933
pbtxn "github.com/matrixorigin/matrixone/pkg/pb/txn"
34+
"github.com/matrixorigin/matrixone/pkg/txn/clock"
3035
"github.com/matrixorigin/matrixone/pkg/util/executor"
3136
"github.com/matrixorigin/matrixone/pkg/util/sysview"
3237
"github.com/stretchr/testify/require"
@@ -110,3 +115,188 @@ func TestColumnsUpgradeAdmissionAndIdempotence(t *testing.T) {
110115
})
111116
}
112117
}
118+
119+
// TestColumnsUpgradeReachesExistingTenants drives the retained 4.0.19 tenant
120+
// hop (design 5.2, routes per D14-2; renumbered by revision 10 onto the
121+
// consolidated ladder): a 4.0.7 account holding any pre-correction
122+
// information_schema identity is rewritten to exactly the published
123+
// identities through the per-account walk, which steps the upstream 4.0.18
124+
// handle and the final vehicle; a current account is a no-op, a mid-hop DDL
125+
// failure leaves the account marker untouched and retries cleanly.
126+
func TestColumnsUpgradeReachesExistingTenants(t *testing.T) {
127+
runtime.RunTest("", func(runtime.Runtime) {
128+
frozen := v4_0_7.Handler.Metadata()
129+
current := versions.Version{Version: frozen.Version, VersionOffset: frozen.VersionOffset, State: versions.StateReady}
130+
columnsDefinition := sysview.InformationSchemaColumnsBinaryFamilyNullDDL()
131+
statisticsDefinition := sysview.InformationSchemaStatisticsDDL
132+
tenantVersion := "4.0.7"
133+
var queuedVersion, queuedRoute bool
134+
var writes []string
135+
failStatistics := false
136+
injected := errors.New("injected STATISTICS create failure")
137+
op := mock_frontend.NewMockTxnOperator(gomock.NewController(t))
138+
op.EXPECT().TxnOptions().Return(pbtxn.TxnOptions{}).AnyTimes()
139+
op.EXPECT().Txn().Return(pbtxn.TxnMeta{}).AnyTimes()
140+
exec := executor.NewMemExecutor2(func(sql string) (executor.Result, error) {
141+
switch {
142+
case strings.HasPrefix(sql, "SELECT reldatabase, relname, account_id FROM mo_catalog.mo_tables"):
143+
return newBootstrapStringResult("mo_catalog"), nil
144+
case sql == versions.LatestVersionSQL:
145+
return recoveryVersionResult(t, current), nil
146+
case strings.HasPrefix(sql, "select version from mo_version"):
147+
// The latest ready version that the route chains from.
148+
return newBootstrapStringResult(frozen.Version), nil
149+
case strings.HasPrefix(sql, "select state from mo_version"):
150+
// The queued forward version has no row yet; the checker
151+
// proceeds to enqueue it with its route.
152+
return executor.Result{}, nil
153+
case strings.HasPrefix(sql, "insert into mo_version"):
154+
// The registered forward version carries the two shared entries.
155+
require.Contains(t, sql, "'4.0.19', 2, 0")
156+
queuedVersion = true
157+
case strings.HasPrefix(sql, "insert into mo_upgrade"):
158+
require.Contains(t, sql, "'4.0.7'")
159+
require.Contains(t, sql, "'4.0.19'")
160+
queuedRoute = true
161+
case strings.HasPrefix(sql, "select create_version from mo_account"):
162+
return newBootstrapStringResult(tenantVersion), nil
163+
case strings.Contains(sql, "relname = 'COLUMNS'"), strings.Contains(sql, "relname = 'columns'"):
164+
return newBootstrapStringResult(columnsDefinition), nil
165+
case strings.Contains(sql, "relname = 'STATISTICS'"), strings.Contains(sql, "relname = 'statistics'"):
166+
return newBootstrapStringResult(statisticsDefinition), nil
167+
case strings.HasPrefix(sql, "select rel_id, rel_logical_id, relkind from mo_catalog.mo_tables"):
168+
return executor.Result{}, nil
169+
case sql == "SELECT mo_ctl('cn', 'GetProtocolVersion', '')":
170+
return newBootstrapStringResult(`{"result":"cn:118"}`), nil
171+
case sql == strings.Replace(sysview.InformationSchemaColumnsDDL, "CREATE VIEW ", "CREATE OR REPLACE VIEW ", 1):
172+
writes = append(writes, sql)
173+
columnsDefinition = sysview.InformationSchemaColumnsDDL
174+
case sql == strings.Replace(sysview.InformationSchemaStatisticsPrefixSubPartDDL, "CREATE VIEW ", "CREATE OR REPLACE VIEW ", 1):
175+
writes = append(writes, sql)
176+
if failStatistics {
177+
return executor.Result{}, injected
178+
}
179+
statisticsDefinition = sysview.InformationSchemaStatisticsPrefixSubPartDDL
180+
case strings.HasPrefix(sql, "update mo_account set create_version = '"):
181+
version := strings.TrimSuffix(
182+
strings.TrimPrefix(sql, "update mo_account set create_version = '"),
183+
"' where account_id = 7")
184+
if version == v4_0_18.Handler.Metadata().Version {
185+
// The walk also steps the upstream 4.0.18 handle; its
186+
// stamp stays inside the walking transaction, so the
187+
// durable account version only moves when the final
188+
// vehicle's stamp commits with the transaction.
189+
return executor.Result{AffectedRows: 1}, nil
190+
}
191+
if version == "4.0.19" {
192+
require.Equal(t, sysview.InformationSchemaColumnsDDL, columnsDefinition,
193+
"the completed tenant must carry the hop's published COLUMNS identity")
194+
require.Equal(t, sysview.InformationSchemaStatisticsPrefixSubPartDDL, statisticsDefinition,
195+
"the completed tenant must carry the hop's published STATISTICS identity")
196+
}
197+
tenantVersion = version
198+
return executor.Result{AffectedRows: 1}, nil
199+
default:
200+
return executor.Result{}, fmt.Errorf("unexpected upgrade SQL: %s", sql)
201+
}
202+
return executor.Result{}, nil
203+
}, op)
204+
s := newServiceForTest("", &memLocker{}, clock.NewHLCClock(func() int64 { return 0 }, 0), nil, exec,
205+
func(s *service) { s.initUpgrade() })
206+
t.Cleanup(s.stopper.Stop)
207+
final := s.getFinalVersionHandle().Metadata()
208+
require.NoError(t, s.doCheckUpgrade(t.Context()))
209+
require.True(t, queuedVersion)
210+
require.True(t, queuedRoute, "a completed 4.0.7 cluster must queue the forward repair")
211+
require.Equal(t, "4.0.19", final.Version)
212+
require.Equal(t, "4.0.7", final.MinUpgradeVersion)
213+
require.Equal(t, uint32(2), final.VersionOffset)
214+
require.Equal(t, int64(defines.MORPCVersion118), final.RequiredProtocolVersion)
215+
216+
// The cluster route has finished; the tenant's persisted account
217+
// version is authoritative. Every leg clears the completed-tenant
218+
// cache the way a fresh login on a new CN observes the account.
219+
current = final
220+
current.State = versions.StateReady
221+
fetchTenant := func() (int32, string, error) { return 7, tenantVersion, nil }
222+
runLeg := func(tenant, columns, statistics string) (bool, error) {
223+
delete(s.mu.tenants, 7)
224+
tenantVersion = tenant
225+
columnsDefinition = columns
226+
statisticsDefinition = statistics
227+
failStatistics = false
228+
writes = nil
229+
return s.MaybeUpgradeTenant(t.Context(), fetchTenant, nil)
230+
}
231+
232+
// A 4.0.7 account holding the NULL-selector COLUMNS generation and
233+
// the SQL NULL SUB_PART STATISTICS is rewritten to exactly the
234+
// published identities.
235+
upgraded, err := runLeg("4.0.7",
236+
sysview.InformationSchemaColumnsBinaryFamilyNullDDL(), sysview.InformationSchemaStatisticsDDL)
237+
require.NoError(t, err)
238+
require.True(t, upgraded)
239+
require.Equal(t, 2, len(writes))
240+
require.Contains(t, writes, strings.Replace(sysview.InformationSchemaColumnsDDL, "CREATE VIEW ", "CREATE OR REPLACE VIEW ", 1))
241+
require.Contains(t, writes, strings.Replace(sysview.InformationSchemaStatisticsPrefixSubPartDDL, "CREATE VIEW ", "CREATE OR REPLACE VIEW ", 1))
242+
require.Equal(t, "4.0.19", tenantVersion)
243+
require.Equal(t, sysview.InformationSchemaColumnsDDL, columnsDefinition)
244+
require.Equal(t, sysview.InformationSchemaStatisticsPrefixSubPartDDL, statisticsDefinition)
245+
246+
// The same holds for the pre-#31160 'binary'-selector generation.
247+
upgraded, err = runLeg("4.0.7",
248+
sysview.InformationSchemaColumnsV110DDL(), sysview.InformationSchemaStatisticsDDL)
249+
require.NoError(t, err)
250+
require.True(t, upgraded)
251+
require.Equal(t, 2, len(writes))
252+
require.Equal(t, "4.0.19", tenantVersion)
253+
254+
// A tenant already holding both published identities is a no-op: a
255+
// completed refresh never churns the definitions (canonicalized
256+
// identity equality; unknown or edited text still fails the check).
257+
upgraded, err = runLeg("4.0.7",
258+
sysview.InformationSchemaColumnsDDL, sysview.InformationSchemaStatisticsPrefixSubPartDDL)
259+
require.NoError(t, err)
260+
require.True(t, upgraded)
261+
require.Empty(t, writes, "a current tenant must not be rewritten")
262+
require.Equal(t, "4.0.19", tenantVersion)
263+
264+
// A mid-hop DDL failure stays visible to login: the account marker
265+
// is untouched, so the next pass re-enters and repairs the failed
266+
// leg. Model a tenant whose COLUMNS is current but whose STATISTICS
267+
// definition is still stale.
268+
delete(s.mu.tenants, 7)
269+
tenantVersion = "4.0.7"
270+
columnsDefinition = sysview.InformationSchemaColumnsDDL
271+
statisticsDefinition = sysview.InformationSchemaStatisticsDDL
272+
failStatistics = true
273+
writes = nil
274+
upgraded, err = s.MaybeUpgradeTenant(t.Context(), fetchTenant, nil)
275+
require.ErrorIs(t, err, injected)
276+
require.False(t, upgraded)
277+
require.Equal(t, "4.0.7", tenantVersion, "the failed hop must not advance the account marker")
278+
require.Equal(t, sysview.InformationSchemaStatisticsDDL, statisticsDefinition,
279+
"the failed create must not persist the new identity")
280+
require.Empty(t, s.mu.tenants, "failed hops must remain retryable")
281+
282+
// The retry completes the tenant by refreshing the stale leg.
283+
failStatistics = false
284+
writes = nil
285+
upgraded, err = s.MaybeUpgradeTenant(t.Context(), fetchTenant, nil)
286+
require.NoError(t, err)
287+
require.True(t, upgraded)
288+
require.Equal(t, []string{
289+
strings.Replace(sysview.InformationSchemaStatisticsPrefixSubPartDDL, "CREATE VIEW ", "CREATE OR REPLACE VIEW ", 1),
290+
}, writes)
291+
require.Equal(t, "4.0.19", tenantVersion)
292+
require.Equal(t, sysview.InformationSchemaColumnsDDL, columnsDefinition)
293+
require.Equal(t, sysview.InformationSchemaStatisticsPrefixSubPartDDL, statisticsDefinition)
294+
295+
// A completed tenant is never refreshed again.
296+
writes = nil
297+
upgraded, err = s.MaybeUpgradeTenant(t.Context(), fetchTenant, nil)
298+
require.NoError(t, err)
299+
require.False(t, upgraded)
300+
require.Empty(t, writes, "a completed tenant must not be refreshed again")
301+
})
302+
}

‎pkg/bootstrap/custom_upgrade.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,14 @@ func (s *service) UpgradeOneTenant(ctx context.Context, tenantID int32) error {
201201
from = v.Metadata().Version
202202
}
203203
}
204+
// A manual upgrade reports success only with the account at the
205+
// cluster's final version. The re-planned loop below still takes
206+
// over after a committed paged 4.0.7 stage, so only a non-pending
207+
// shortfall is terminal here instead of being cached as success.
208+
if !pendingV407 && from != currentCN.Version {
209+
return moerr.NewInvalidInputNoCtxf("cannot upgrade tenant version %s to current cn version %s",
210+
from, currentCN.Version)
211+
}
204212
return nil
205213
},
206214
opts)

‎pkg/bootstrap/service_statistics_upgrade_test.go‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
"github.com/golang/mock/gomock"
2424
"github.com/matrixorigin/matrixone/pkg/bootstrap/versions"
25+
"github.com/matrixorigin/matrixone/pkg/bootstrap/versions/v4_0_18"
2526
"github.com/matrixorigin/matrixone/pkg/bootstrap/versions/v4_0_6"
2627
"github.com/matrixorigin/matrixone/pkg/bootstrap/versions/v4_0_7"
2728
"github.com/matrixorigin/matrixone/pkg/common/moerr"
@@ -50,9 +51,10 @@ func TestPublishedCatalogUpgradeRoutes(t *testing.T) {
5051
offset uint32
5152
hops [][2]string
5253
}{
53-
{name: "4.1", version: "4.0.1", offset: 1, hops: [][2]string{{"4.0.1", "4.0.2"}, {"4.0.2", "4.0.3"}, {"4.0.3", "4.0.4"}, {"4.0.4", "4.0.5"}, {"4.0.5", "4.0.6"}, {"4.0.6", "4.0.7"}, {"4.0.7", "4.0.18"}}},
54-
{name: "4.2", version: "4.0.6", offset: 5, hops: [][2]string{{"4.0.6", "4.0.7"}, {"4.0.7", "4.0.18"}}},
55-
{name: "4.0.7", version: "4.0.7", offset: v4_0_7.Handler.Metadata().VersionOffset, hops: [][2]string{{"4.0.7", "4.0.18"}}},
54+
{name: "4.1", version: "4.0.1", offset: 1, hops: [][2]string{{"4.0.1", "4.0.2"}, {"4.0.2", "4.0.3"}, {"4.0.3", "4.0.4"}, {"4.0.4", "4.0.5"}, {"4.0.5", "4.0.6"}, {"4.0.6", "4.0.7"}, {"4.0.7", "4.0.18"}, {"4.0.18", "4.0.19"}}},
55+
{name: "4.2", version: "4.0.6", offset: 5, hops: [][2]string{{"4.0.6", "4.0.7"}, {"4.0.7", "4.0.18"}, {"4.0.18", "4.0.19"}}},
56+
{name: "4.0.7_frozen", version: "4.0.7", offset: v4_0_7.Handler.Metadata().VersionOffset, hops: [][2]string{{"4.0.7", "4.0.19"}}},
57+
{name: "4.0.18_main_era", version: "4.0.18", offset: v4_0_18.Handler.Metadata().VersionOffset, hops: [][2]string{{"4.0.18", "4.0.19"}}},
5658
} {
5759
t.Run(tc.name, func(t *testing.T) {
5860
runtime.RunTest("", func(runtime.Runtime) {
@@ -72,12 +74,12 @@ func TestPublishedCatalogUpgradeRoutes(t *testing.T) {
7274
}, &testTxnOperator{})
7375
s := newServiceForTest("", &memLocker{}, clock.NewHLCClock(func() int64 { return 0 }, 0), nil, exec, func(s *service) { s.initUpgrade() })
7476
t.Cleanup(s.stopper.Stop)
75-
require.Equal(t, "4.0.18", s.GetFinalVersion())
77+
require.Equal(t, "4.0.19", s.GetFinalVersion())
7678
require.Equal(t, uint32(5), v4_0_6.Handler.Metadata().VersionOffset)
7779
require.NoError(t, s.doCheckUpgrade(t.Context()))
7880
require.Len(t, upgrades, len(tc.hops))
7981
for i, hop := range tc.hops {
80-
require.Contains(t, upgrades[i], fmt.Sprintf("values ('%s', '%s', '4.0.18',", hop[0], hop[1]))
82+
require.Contains(t, upgrades[i], fmt.Sprintf("values ('%s', '%s', '4.0.19',", hop[0], hop[1]))
8183
}
8284
})
8385
})

‎pkg/bootstrap/service_upgrade.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,14 @@ func (s *service) checkUpgradeRecovery(target versions.Version, txn executor.Txn
499499
(u.State != versions.StateCreated && u.State != versions.StateUpgradingTenant && u.State != versions.StateReady) {
500500
return &terminalUpgradeError{moerr.NewInvalidStateNoCtxf("cannot resume invalid upgrade step %s", u.String())}
501501
}
502+
// Offset-only legs target only the frozen 4.0.7 stage, whose only
503+
// durable per-account progress marker cannot identify two offsets
504+
// of the same version. Reject resumption here exactly as the
505+
// pre-mutation check rejects creating it.
506+
if u.FromVersion == v4_0_7.Handler.Metadata().Version &&
507+
u.ToVersion == v4_0_7.Handler.Metadata().Version {
508+
return &terminalUpgradeError{moerr.NewInvalidStateNoCtx("unsupported in-progress 4.0.7 offset-only upgrade; 4.0.7 is frozen and further migrations require a new catalog version")}
509+
}
502510
supported := false
503511
for _, h := range s.handles {
504512
v := h.Metadata()
@@ -512,6 +520,16 @@ func (s *service) checkUpgradeRecovery(target versions.Version, txn executor.Txn
512520
return &terminalUpgradeError{moerr.NewInvalidStateNoCtxf("cannot resume unsupported upgrade step %s", u.String())}
513521
}
514522
}
523+
// A retained route to the frozen 4.0.7 stage needs the same catalog
524+
// admission upstream enforces before creating it: a final above 4.0.7
525+
// reaches this resume path without any other admission check.
526+
// canResumeUpgrade already pinned the route to the registered frozen
527+
// handle's offset.
528+
if target.Version == v4_0_7.Handler.Metadata().Version {
529+
if err := rejectLegacyCDCTasks(txn); err != nil {
530+
return err
531+
}
532+
}
515533
return nil
516534
}
517535

0 commit comments

Comments
 (0)