Skip to content

fix(sql): evaluate RANDOM_BYTES independently for each row - #33552

Merged
XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/random-bytes-volatility
Dec 2, 2026
Merged

XuPeng-SH merged 14 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/random-bytes-volatility

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Dec 1, 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:

Related to #33531. The original IVF PRE example with RAND() already returns a full page on main. The same class of error is reproducible on main with RANDOM_BYTES().

What this PR does / why we need it:

RANDOM_BYTES(n) draws fresh bytes for each non-null row. Its signed, unsigned and generic overloads all lacked the volatility flag. This let constant-length calls share one draw across a batch. It also let index rewrites evaluate a random predicate once to select candidates and again after the join. A row that passed the first draw could disappear after the top ten candidates had already been chosen.

Mark all three overloads volatile. The evaluator and the IVF and full-text planners already honor this property. A stable IVF PRE predicate remains eligible for the vector index. An unsafe random predicate can use the existing exact scan, which can cost more on large tables.

Rename before upgrade

The official v4.2.8 release (10d204b, Linux arm64) created the source tables and renamed them before shutdown. On the previous PR head, a fresh dump of a twice-renamed table omitted both anonymous CHECK ordinals. Loading into a different table in the same database failed with error 3822 while the source existed. Physical v4.2.8 CHECKs that used RANDOM_BYTES also exposed error 20301 during DUMP because their stored expression trees used the release's length conversions and binary type metadata.

The catalog recovery verifies the full ordered list of CHECK declarations from the relation's retained CREATE before recovering names from a previous table name. Archive CREATE validation still verifies its declared source. When a stored CHECK or generated column contains RANDOM_BYTES, the planner can rebind the original SQL using v4.2 argument casts, BLOB metadata, binary assignment and integer comparison rules. Format 3 carries the verified binding across restore.

With the new server on the released data directory, all seven upgrade cases passed through SQL and restart. The two anonymous CHECKs restored with distinct target names, and an explicitly named __mo_chk_1 retained its schema-wide uniqueness. Constant, signed-column and unsigned-column lengths worked. The stored generated value survived byte-for-byte, a later insert produced the requested length, and invalid writes continued to return 3819. Four catalog wire captures from the release exercise the same binding proof in the planner tests.

The final binary at e4d0341deb also passed two consecutive runs of the 188-statement DUMP/LOAD BVT, all 19 RANDOM_BYTES coercion checks, and all 75 filtered IVF checks. The PR-selected unit tests passed under -race (38 tests across six packages, zero skips). make static-check-changed selected the full graph because the PR changes protobuf definitions. Both molint and golangci-lint passed with zero issues.

Verification

  • Reproduced on upstream 38c68d02ca with 2,400 rows and 401 guaranteed matches. A sparse random predicate with LIMIT 10 returned 0–7 rows in all 20 PRE runs. The exact query returned ten each time. The fixed PRE and exact queries both returned ten in all 20 runs. A second CN also returned a full page.
  • Added a regression through the real vector evaluator. With a constant length and two rows, all three overloads returned a broadcast constant on the base commit. The assertion checks the vector representation and is independent of the generated byte values. Added a SQL regression to the existing IVF fixture with a page size guaranteed by the data.
  • Verified one random filter in the execution plans for both full-text implementations, index use for deterministic IVF predicates, prepared execution, NULL, bounds, invalid lengths and an empty input.
  • A four-row insert using DEFAULT (RANDOM_BYTES(16)) yielded one distinct value on the base commit and four on the fixed build.
  • A local 2,400-row stable-predicate control produced identical plans and top-ten IDs. Across 12 alternating paired batches of 48 statements per build, median times were 2.952 ms on base and 2.949 ms on the fix.
  • All 324 statements in five distributed SQL fixtures passed. The full function package passed under the race detector. Targeted planner tests, build, vet, molint and incremental golangci-lint passed.

Random-byte generation cost

Both literal and column lengths use the same coercion path. For each group of valid rows, request only the needed bytes from crypto/rand, capped at 32 KiB, then give each row a disjoint slice. NULL rows consume no bytes. The output vector owns the finished values before the scratch buffer is reused. A partial entropy read is rejected before the group becomes visible. The regression tests use a deterministic byte stream to check both inline and large values across refills.

Paired SQL runs compare the batch change with 6901c0c90a, which already returns independent values. On a local 100,000-row table, median fixed lengths of 16 and 1,024 bytes took 17.66 → 16.43 ms and 141.13 → 122.04 ms respectively. Varying 15/16 and 1,023/1,024-byte lengths took 19.70 → 17.52 ms and 139.10 → 122.51 ms. A cohort of eight concurrent clients running three 1,024-byte queries each took 1,004 → 756 ms. A single-row call took 0.319 → 0.336 ms. The two-CN SQL checks, 324 fixture statements, planner tests, package race, build, vet and incremental static checks passed on the batch change.

For an 8,192-row vector with 1,024-byte values, the function benchmark went from 8,195 to 4 allocations per evaluation with result storage already warmed. A 10,000-row insert using the default with a unique constraint also produced 10,000 distinct values on both compared builds.

Vector materialization

Reuse the existing vector bulk-append operation for multiple BLOB rows. The vector still owns each value, nullable rows remain nullable, and a scalar result uses the single-value append. Each row gets independent cryptographically secure bytes.

A second paired SQL run from 44382bb0a9 to a8fdf26b91 gave these local medians in ms:

Workload Previous Bulk append
100,000 rows, fixed 16 bytes 17.79 15.25
100,000 rows, varying 15/16 bytes 17.45 15.33
100,000 rows, distinct hex of 16-byte values 44.97 41.39
100,000 rows, fixed 1,024 bytes 134.52 128.03
8 concurrent clients, 3 large statements each 879.4 815.5
32 rows, fixed 16 bytes 0.478 0.503
Single row, fixed 16 bytes 0.323 0.310

Generating the 102.4 MB of cryptographically secure bytes alone took about 97 ms locally. Both the function and vector packages passed under the race detector, and that revision passed the two-CN SQL checks, 324 SQL fixture statements and incremental static checks.

Upgrade and restore

An already-folded default keeps its stored value after an in-place upgrade, including when copied by CREATE TABLE LIKE. To get a fresh draw per future row, reapply the default with ALTER TABLE … ALTER COLUMN … SET DEFAULT (RANDOM_BYTES(16)). Ordinary CREATE and ALTER use the current determinism rules for generated columns and CHECK constraints.

Administrator-only LOAD TABLE can create a missing target from the archive and installs the data in the same transaction. DUMP TABLE renders the current replayable definition from the live catalog, including indexes added after the original CREATE. Missing-target replay uses the archive's fingerprints to resolve distinct parse candidates for older SQL. A renamed anonymous CHECK receives the target-local name, with the archived name used for schema and expression verification. Explicit CHECK names are part of the schema identity.

An in-place table rename now records the ordinal of a v4.2.9 anonymous CHECK while its original CREATE still identifies the table. CN and TN persist the same CHECK metadata. LOAD can verify the source names together with the released default collation against both stored schema fingerprints.

Tested a shutdown upgrade from the official v4.2.9 binary using copies of the same data directory. Before the fix, loading a copy while the renamed source existed returned 3822. After a restart on the fixed build, simple and chained renames and a combined column/table rename all restored with the source present. The restored rows matched and invalid inserts returned 3819. A user-declared __mo_chk_1 still returned 3822 while the source owned the name. The rebased source passed all 36 changed Go tests under -race, 188 DUMP/LOAD statements twice, 19 RANDOM_BYTES statements and 75 IVF statements. The protobuf change triggered full-graph SCA. molint passed and golangci-lint reported zero issues.

If a previous writer's CREATE text omitted schema details, supply the recorded complete CREATE in create_sql in a copy of the archive and keep its fingerprints. A real v4.2.9 archive verified this with both the main and index objects. The stale original was rejected without leaving a table. The corrected archive restored the stored generated bytes, passed an indexed read, and preserved CHECK enforcement on subsequent writes. The original v4.2.9 fixture also passed rollback, truncate and reload, re-export, and restart checks.

Verification on the rebased head using upstream 6674873fdf included 154 of 154 DUMP/LOAD statements in each of two runs, 19 RANDOM_BYTES coercion statements, and 73 IVF statements. The focused race checks, build and incremental static checks passed.

Restore fixes verified on 324276b

DUMP fingerprints the constraints the source catalog enforces. A CHECK retained only in v4.1.0 CREATE text no longer becomes active during restore. CREATE and ALTER retain the assigned suffix for anonymous CHECKs. A restored table can use its own name even after an earlier CHECK was dropped. Explicit constraint names preserve their schema-wide identity. Missing-target validation uses an isolated process with the archive candidate's SQL mode, and the caller keeps its original mode for subsequent statements.

  • Using the official v4.1.0 binary, created a table that declared a positive-ID CHECK and accepted negative IDs. Took a checkpoint and tested copies of the same data with previous head 0a53998bfc and new head 324276bfd6. Previously an unchanged empty table rejected its own dump, and a recreated table rejected negative IDs. With the fix, the original and renamed empty targets loaded, a full restore preserved the negative row, and the restored table accepted another one.
  • On two CNs, all 188 DUMP/LOAD, 19 RANDOM_BYTES and 73 IVF statements passed. The existing ALTER suite passed 469 statements and skipped six. The checks include a surviving anonymous CHECK with a numbering gap, a conflicting explicit lookalike, a historical zero-date default, and ordinary strict-mode CREATE and INSERT controls.
  • The native build passed. Across four packages, 159 focused tests passed under the Go race detector, including concurrent publication across CNs. Incremental golangci-lint reported zero issues.

A separate direct v4.1.0 upgrade without a checkpoint panicked during TN WAL replay on both upstream ec945a6323 and this head. Both reported the same type mismatch for __mo_index_pri_col before accepting SQL. The restore verification above uses the checkpointed source.

@qodo-code-review

qodo-code-review Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

fix(sql): mark RANDOM_BYTES volatile so each row gets its own draw

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Flags all three RANDOM_BYTES overloads volatile so constant-length calls draw per row.
• Stops IVF PRE and full-text index rewrites from sampling a random predicate twice, which shortened
 result pages.
• Adds a vector-evaluator regression test and an IVF SQL fixture that guarantees a full page.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed executor and overload metadata jointly define one end-to-end SQL function behavior: generating random BLOB values and preserving per-row volatile evaluation.
  • Query predicates and projections are consumers of that same function outcome, not independent functional scopes.
Behavioral complexity 🟡 Medium 🧩 Interacting branches, Data transformation

  • Before, each row validated its length, read exactly its own buffer, and appended immediately.
  • After, rows are grouped under byte and row limits, NULLs consume no entropy, one shared buffer is partitioned into slices, and errors are reported after valid predecessors.
  • The new correctness condition is that cumulative byte offsets, NULL positions, partial batches, entropy read lengths, and planner volatility semantics remain aligned for every row.
Potential damage 🟡 Medium 🩹 Incorrect results

  • If the changed batching or volatile classification is wrong, a query can receive incorrect random bytes or evaluate a RANDOM_BYTES predicate with the wrong per-row behavior.
  • Effects are transient query results rather than persistent state or external side effects.
  • Rerunning the query after correcting the code restores the capability; no stored-data repair or external compensation is indicated.
Assessed commit a8fdf26
Diagram

graph TD
  A["RANDOM_BYTES overloads"] --> B["volatile flag"] --> C["Function evaluator"]
  B --> D["IVF PRE planner"]
  B --> E["Full-text planner"]
  C --> F["Per-row draw"]
  G["IVF SQL fixture"] --> D
Loading
High-Level Assessment

The volatile flag is the existing mechanism the evaluator and both planners already use to decide per-row evaluation and rewrite safety, so setting it on the registrations is the minimal, consistent fix. Alternatives considered: special-casing RANDOM_BYTES inside the evaluator to skip constant folding, which would leave the planner's double-sampling bug in place; and making the planners ignore randomness, which would change behavior for other functions. Both were dismissed. The trade-off is that random predicates on large tables now use the exact scan, which can cost more, and the PR states this openly.

Files changed (5) +41 / -14

Bug fix (1) +3 / -0
list_builtIn.goSet volatile flag on the three RANDOM_BYTES overloads +3/-0

Set volatile flag on the three RANDOM_BYTES overloads

• Adds volatile: true to the int64, uint64 and generic (T_any) RANDOM_BYTES overloads. The evaluator and planners then treat each call as a fresh draw rather than a shareable constant.

pkg/sql/plan/function/list_builtIn.go

Tests (4) +38 / -14
func_random_bytes_test.goAdd per-row evaluation regression test for all overloads +26/-0

Add per-row evaluation regression test for all overloads

• Adds a table-driven test that passes a constant length with two rows through RunFunctionDirectly for each overload. It asserts the result is not a constant vector and has length two.

pkg/sql/plan/function/func_random_bytes_test.go

proven_pure_foldable_test.goMove random_bytes into the volatile exclusion list +1/-14

Move random_bytes into the volatile exclusion list

• Removes random_bytes from the clean-flagged exclusions and adds it to the flag-carried exclusions. This matches the new volatile flag, since the pure-foldable scan now rejects it through the flag.

pkg/sql/plan/function/proven_pure_foldable_test.go

vector_filtered_search_ivfflat.sqlAdd IVF PRE query with random filter and guaranteed full page +6/-0

Add IVF PRE query with random filter and guaranteed full page

• Adds a query combining a deterministic id range that guarantees ten matches with a random_bytes predicate under mode=pre. The query exposes the double-sampling bug if the predicate is re-evaluated after candidate selection.

test/distributed/cases/vector/vector_filtered_search_ivfflat.sql

vector_filtered_search_ivfflat.resultRecord expected result for the random filter IVF query +5/-0

Record expected result for the random filter IVF query

• Adds the expected output for the new IVF PRE query, which returns a count of 10 as the page is always full with the fix.

test/distributed/cases/vector/vector_filtered_search_ivfflat.result

@matrix-meow matrix-meow added the size/S Denotes a PR that changes [10,99] lines label Dec 1, 2026
@mergify

mergify Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review

Grey Divider

Tip of the day
💡 Did you know, you can pick a display mode instead of tweaking every Display option by hand

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@XuPeng-SH

XuPeng-SH commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 6901c0c90a6d6e9f9eddf686a5b3c622b74dcf5b

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: 6901c0c90a6d6e9f9eddf686a5b3c622b74dcf5b

Assessment: approve

Marking all three RANDOM_BYTES overloads volatile uses the existing evaluator and planner safety mechanisms. It prevents constant broadcasting and unsafe predicate replay; stable IVF predicates remain eligible for index access. No actionable unresolved findings were identified.

Model: gpt-6.1-terra / max

Session: 01a22aff-bb68-7e31-ae71-ee4ab48ad9d0 · slot 0 · generation 45

Validation:

  • The isolated preflight, native-input provenance audit, focused RANDOM_BYTES tests, full function-package test and git diff --check passed.

  • The new per-row test failed for all three overloads against a byte-verified base registry overlay, as expected.

  • A one-CN public SQL probe passed literal, prepared, default, NULL, invalid-length and empty-table cases. It also verified exact fallback for the volatile IVF predicate and index use for a stable control.

  • An initial public probe incorrectly treated a descending generate_series as empty and failed; the corrected empty-table probe passed. Both logs and their receipts were retained.

Limitations:

  • The public uniqueness observations use 16-byte random outputs and are probabilistic.

  • The full distributed SQL fixture, multi-CN checks, race run and performance benchmark reported by the author were not independently rerun.

@XuPeng-SH

XuPeng-SH commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 44382bb0a9a061ae9497a719c4263bdd7c0cdcfc

"interrupted"

@XuPeng-SH
XuPeng-SH force-pushed the fix/random-bytes-volatility branch from 0a53998 to 324276b Compare December 1, 2026 17:37
@XuPeng-SH

XuPeng-SH commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 324276bfd6773f4f1672ba6404f1f4d5c6fe338b

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: 324276bfd6773f4f1672ba6404f1f4d5c6fe338b

Assessment: request_changes

The volatility fix reuses the existing evaluator and planner safeguards, and bounded entropy batching reuses vector bulk append. The earlier direct restore and SQL-mode cases pass, but a legacy anonymous CHECK can still lose its naming provenance during ALTER, preventing a renamed restore in the source database.

Model: gpt-6.1-terra / max

Session: 01a22b07-00b6-7e32-b0a1-3099d0b867c7 · slot 1 · generation 39

  • P2 pkg/frontend/table_dump.go:518: A table created on v4.2.9 with an anonymous CHECK is upgraded, then an ALTER adds or removes a CHECK before the table is dumped.
    Impact: The new dump can render the surviving anonymous CHECK as explicitly named __mo_chk_1 or __mo_chk_2. Loading it into a differently named missing table in the same database then fails with duplicate CHECK name error 3822 while the source table exists.
    Evidence: v4.2.9 assigned __mo_chk_N names without recording an ordinal. The current ALTER COPY path rewrites those names as explicit constraints without populating GeneratedNameOrdinal, so this fallback cannot establish their anonymous origin. The released-catalog planner model and dump probe reproduce that metadata transition; a separate one-CN explicit-name control confirms the resulting namespace collision. Preserve proven anonymous-name provenance from the original declaration before ALTER rewrites it, while continuing to preserve explicitly authored names.

Validation:

  • Private runtime preflight, native-input provenance, fixture checksum, and diff checks passed.

  • Focused RANDOM_BYTES, historical-expression planner, and frontend DUMP tests passed on the assigned head; receipt checks/1796148336979483256-3.json.

  • Single-CN probes passed the earlier anonymous-ALTER and strict-mode controls and restored the supplied v4.2.9 archive, including later writes and corruption rollback; receipts checks/1796148668594525703-3.json and checks/1796148832180733722-3.json.

  • Released-metadata model probes demonstrated the ordinal loss, and a separate public SQL control demonstrated the resulting explicit-name collision; logs legacy-ordinal-probes.log, legacy-add-check-probe.log, and legacy-add-public-control.log.

Limitations:

  • The reported finding combines a model of the released catalog metadata with a public SQL collision control; that exact sequence was not independently run through a live v4.2.9 upgrade.

  • Full distributed CI and the author's reported multi-CN and race checks were not independently rerun.

@XuPeng-SH

XuPeng-SH commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: c4701f18c479194844116194841ee553a365a2df

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: c4701f18c479194844116194841ee553a365a2df

Assessment: request_changes

The volatility fix reuses the existing evaluator and vector-planner safeguards, and the restore work extends the existing schema and binding verification machinery. The prior COPY-ALTER finding is fixed for the tested cases, but an in-place table rename still loses released anonymous CHECK provenance and prevents a supported same-database restore.

Model: gpt-6.1-terra / max

Session: 01a2319b-6eff-73c0-b59b-ebce3800e538 · slot 2 · generation 16

  • P2 pkg/sql/plan/build_alter_table.go:1556: Upgrade a v4.2.9 table created with an anonymous CHECK, rename the table with ALTER TABLE, then dump it and load the archive under another name in the same database while the renamed source remains.
    Impact: LOAD TABLE fails with duplicate CHECK name error 3822 because the archive treats the released generated name as an explicit schema-wide name. The archive loads after the source is dropped, but it cannot create the intended concurrent copy.
    Evidence: The recovered ordinal is passed to COPY ALTER, but buildAlterTableInplace resolves the original definition again at pkg/sql/plan/build_ddl.go:7701. Storage retains the released __mo_chk_1 name and the old CREATE declaration on rename, so later recovery cannot match that declaration to the new table name. The single-CN release-shaped catalog probe in rename-integration.log reproduces error 3822 through SQL rename, dump and load; the same archive succeeds after dropping the source, and a current anonymous-CHECK control succeeds with its source present. Preserve the recovered provenance durably across in-place rename while retaining explicit-name behavior.

Validation:

  • Private /tmp and loopback preflight passed. Retained native artifacts matched all 195 current inputs and seven recorded outputs.

  • Focused RANDOM_BYTES, planner, frontend and released-archive tests passed, including a single-CN v4.2.9 archive restore, subsequent write, truncate/reload and corrupt-archive rollback.

  • A further 101 selected replay, ALTER, load and volatility tests passed. The changed single-CN legacy TINYTEXT upgrade test also passed.

  • The release-shaped rename integration probe reproduced the reported failure and passed its source-drop and current-schema controls.

  • Four fixture manifests and five object sizes and hashes were verified; git diff --check passed. Commands, source fingerprints, exits and retained logs are reconciled in validation-audit.json.

Limitations:

  • The rename reproduction seeded a release-shaped catalog using the repository's engine delete/create upgrade-test mechanism; it did not run an actual v4.2.9 binary upgrade.

  • The full changed mo-tester BVT, multi-CN workload and performance benchmarks were not independently rerun.

@XuPeng-SH

XuPeng-SH commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: f59b4ec77c65d2423a1d620622ab6b6661adbbef

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: f59b4ec77c65d2423a1d620622ab6b6661adbbef

Assessment: request_changes

The earlier failure when a released table is renamed after upgrading is fixed for the reported case. A related restore failure remains when the table was renamed before upgrading. The RANDOM_BYTES change otherwise reuses the existing volatility and vector-append mechanisms, and the tested LOAD rollback path preserved transaction state.

Model: gpt-6.1-terra / max

Session: 01a22b07-00b6-7e32-b0a1-3099d0b867c7 · slot 1 · generation 39

  • P2 pkg/sql/plan/check_constraint_rename.go:42: A v4.2.8 table with an anonymous CHECK is renamed on the released binary, then upgraded, dumped, and loaded under another name in the same database while the source remains.
    Impact: The new dump loses the CHECK’s anonymous provenance and LOAD fails with error 3822 because it tries to reuse the source’s schema-wide __mo_chk_1 name. For a historical CHECK containing RANDOM_BYTES, ordinary CREATE cannot recreate the target as a workaround because the expression is now rejected as nondeterministic.
    Evidence: The v4.2.8 source assigns __mo_chk_N to anonymous CHECKs and its in-place rename changes the table name without rewriting the retained CREATE SQL. TableCheckDeclarationNames requires that SQL to identify the current table, so this call cannot recover the ordinal after a pre-upgrade rename. A one-CN public probe seeded that released catalog shape, including legacy charset metadata and a CHECK from the v4.2.9 archive; the dump omitted check_ordinals and the same-database LOAD returned 3822. The archive loaded after dropping the source, and the post-upgrade-rename control passed. Recover or otherwise safely preserve the pre-rename provenance while retaining explicit-name lookalike behavior, and cover this upgrade ordering.

Validation:

  • Private /tmp and loopback preflight passed; the copied native build matched 195 current inputs and seven recorded outputs.

  • Thirty-six selected evaluator, planner, frontend and CN tests passed. The separately selected TN rename wire-metadata test also passed.

  • The release-shaped pre-upgrade rename probe reproduced error 3822 with both an ordinary CHECK and a historical RANDOM_BYTES CHECK; the post-upgrade rename control passed.

  • A one-CN public probe restored the supplied v4.2.9 archive, verified stored values and later writes, and passed truncate/reload and corrupt-object rollback checks.

  • An injected failure immediately after ReplaceDef followed by COMMIT preserved an existing target’s bindings and left no newly created target.

  • Fixture size and SHA-256 checks and git diff --check passed. Command receipts and logs are reconciled in validation-audit.json.

Limitations:

  • The pre-upgrade rename catalog was seeded to the released shape; the probe was not an independently executed physical release upgrade. The PR reports a physical v4.2.9 upgrade for the post-upgrade rename case.

  • The author’s full distributed SQL, multi-CN, race and performance runs were not independently repeated. The fixture identifies v4.2.9 as its producer; the current 4.2 hotfix inventory was not independently verified.

@gouhongshen gouhongshen 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.

Codex automated review

I reviewed the full diff of #33552 (10 commits, 57 files) at head f59b4ec against origin/main, traced each change from its prior behavior, and found no new blocking or non-blocking defect to report. Marking all three RANDOM_BYTES overloads volatile is the correct and complete fix for the shared-draw bug: RunFunctionDirectly (pkg/sql/plan/function/function.go) folds constant-input non-volatile calls to one evaluated row and broadcasts the result, and the same flag gates plan-time constant folding, the IVF/full-text/scalar-vector index rewrites through containsVolatileFunction, CTE identity, and the RETURNING and functional-index rejections, so fresh bytes are now drawn per row on every statement path that previously collapsed or double-evaluated them; the new PRE regression in vector_filtered_search_ivfflat.sql pins the full-page result. The rewritten randomBytesWithReader draws at most 32 KiB per batch and gives each non-null row a disjoint slice; I verified the bounds (sizes capped at 1024 and stored as uint16, the headroom arithmetic keeps byteCount at or below 32 KiB), that vector.AppendBytesList deep-copies into the vector before the scratch buffer is reused, that skipping FunctionResult.validateText is equivalent because the BLOB result type carries a binary charset, that NULL rows consume no entropy and append correctly in both the single- and multi-row paths, that partial entropy reads are now rejected, that an invalid row errors after its valid predecessors are appended (prior semantics), and that the const-vector panic in AppendBytesList is unreachable because volatile functions are never evaluated through the scalar fold path; the new func_random_bytes_test.go covers mixed lengths, nulls, buffer refills, coercion and error paths. The restore machinery added across the later commits (check_ordinals recording, RecoverGeneratedCheckOrdinals, ALTER ordinal assignment, in-place rename parity through AlterTableRenameTable.checks and the tae catalog apply, LOAD auto-create from the archive under the archive's SQL mode with a header rewrite, renamed-check alias matching) is internally consistent, and the regenerated pb files match the new proto fields; gofmt reports no issues in the 34 changed non-pb Go files. The prior mo-bot review at this same head carries one open, unaddressed P2 at pkg/sql/plan/check_constraint_rename.go:42 (a CHECK renamed on a pre-upgrade released binary loses anonymous provenance and a same-database LOAD fails with error 3822); per review rules I have not duplicated it, and since the design doc explicitly scopes in-place-rename ordinal verification to retained CREATE text that still identifies the source table, that known limit remains owned by that finding. Limitations: no changed test package could be executed here. go test -c ./pkg/sql/plan/function exits 1 with a fatal missing 'jemalloc.h' through pkg/common/malloc's thirdparties/install include path, and CGO_ENABLED=0 builds fail on a pre-existing mpool undefined malloc.NewSimpleCAllocator error unrelated to this PR; building the thirdparties prerequisite was not permitted. A saved go list -deps -test -e -json snapshot for pkg/sql/plan, pkg/sql/plan/function, pkg/frontend and pkg/vm/engine/disttae shows no dependency or cgo-metadata errors beyond those absent headers. Conclusions therefore rest on static analysis of the head plus the unit/BVT coverage present in the diff; the author's distributed SQL fixtures, two-CN runs and race runs were not independently executed.

@XuPeng-SH

XuPeng-SH commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: e4d0341debb588bc4b91ca18d7af1c799c92fc7b

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: e4d0341debb588bc4b91ca18d7af1c799c92fc7b

Assessment: request_changes

The restore changes contain three actionable defects affecting historical expression semantics, released index visibility, and generated CHECK names. The added compatibility mechanisms reuse existing binding and metadata owners and are justified by the restore requirements, but these paths need correction. The previously reported pre-upgrade rename case appears addressed; the earlier RANDOM_BYTES binding fix remains incomplete for SQL-only v1 archives.

Model: gpt-6.1-terra / max

Session: 01a2350e-851d-7031-94fc-615272373c71 · slot 2 · generation 20

  • P2 pkg/sql/plan/table_dump_binding.go:1274: Load a v4.2.8 SQL-only v1 archive into a missing table when its CHECK compares a RANDOM_BYTES expression with a narrower integer column. For example, use nullable columns n TINYINT and s VARCHAR(300) with CHECK (LENGTH(RANDOM_BYTES(LENGTH(s))) > n), then insert n=1 and a 256-byte s after restore.
    Impact: The restored CHECK can accept a row that the released binding rejects, silently changing the table's constraint semantics.
    Evidence: RecoverTableDumpV1Bindings passes a nil supplied definition, so this condition omits the released RANDOM_BYTES binding candidate and verifies only the newly rebound expression. The released binder narrows a nonliteral integer peer to the column domain; the current binder preserves the wider domain unless ReleasedRandomBytesForTableDump is set (pkg/sql/plan/base_binder.go:9778). Reconstruct the release binding where it can be established, or reject an ambiguous v1 restore, and cover this comparison through missing-target LOAD.

  • P2 pkg/frontend/table_dump.go:494: After upgrading a v4.2.8 table whose index was made INVISIBLE, dump it and load the archive into a missing table.
    Impact: The new table recreates that index as visible, and the schema fingerprint can still match, so restore silently changes the index's visibility.
    Evidence: Released index metadata lacks the newer visibility marker. The context-free renderer defaults an unset marker to visible (pkg/sql/plan/build_show_util.go:105), while the authoritative value is in mo_indexes.is_visible (pkg/catalog/index_visibility.go:19). The DUMP path passes the unreconciled relation definition to both fingerprinting and CREATE rendering. Reuse catalog visibility reconciliation on an owned definition for rendering and matching, while preserving legacy archive compatibility.

  • P2 pkg/sql/plan/build_ddl.go:4523: Dump a table created as CREATE TABLE src (v INT, CONSTRAINT dst_chk_2 CHECK (v > 0), CHECK (v < 100)), then load it as dst in a different, otherwise empty database.
    Impact: The valid archive cannot create the requested target: its anonymous second CHECK is assigned dst_chk_2, which duplicates the preserved explicit constraint name.
    Evidence: DUMP retains explicit CHECK names and emits generated checks anonymously (pkg/frontend/table_dump.go:501). Replay derives the anonymous name solely from the destination name and ordinal, and appendCheckDef rejects the duplicate (pkg/sql/plan/build_ddl.go:5100). Allocate a legal nonconflicting generated name while preserving explicit names, and carry the resulting alias through fingerprint verification.

Validation:

  • The assigned preflight passed; receipt checks/1796186683598829716-3.json and preflight.log.

  • git diff --check passed; receipt checks/1796186966539324151-3.json and diff-check.log.

  • The four release fixture manifests and five referenced object sizes and SHA-256 hashes matched; receipt checks/1796186978852948673-3.json and fixtures.log.

  • A retained native-artifact provenance comparison matched 195 tracked inputs and seven recorded outputs; receipt checks/1796187300799027318-4.json and native-provenance.log.

  • The review plan and discussion assessment were written in the assigned diagnostic directory. The assessment was verified to cover all 24 discussion_index keys exactly once.

Limitations:

  • No current-head Go test was executed. The focused test stopped before compilation because the checkout lacks its CGo prerequisites; local Go is 1.26.6 while the module requires 1.27.1, and toolchain bootstrap timed out. These are environment diagnostics, not test passes or product-test failures. The corresponding logs and receipts are focused-plan-test.log with checks/1796186767557003260-3.json, go-list.log with checks/1796186773388566628-3.json, and go-toolchain-bootstrap.log with checks/1796186820051964548-3.json.

  • The three findings are supported by source tracing and released-source evidence; their concrete examples were not executed locally. The supplied local_validation list contains no matching retained execution receipts for the author's reported upgrade and test runs.

  • All relative receipt and log paths above are under /mnt/nvme/mo-bot-55-live/state/jobs/7819864609438fd2c018502a/attempt-4.

@XuPeng-SH

XuPeng-SH commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 4f9b650b7cd4b3377b0c114994f56afd309f50a2

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: 4f9b650b7cd4b3377b0c114994f56afd309f50a2

Assessment: request_changes

The RANDOM_BYTES fix reuses the existing volatility and vector-append mechanisms. The latest revision addresses the three specific cases in the prior review, but two related restore defects remain: an anonymous CHECK can collide with a constraint on another table, and a released anonymous-CHECK archive cannot be reloaded into certain existing targets.

Model: gpt-6.1-terra / max

Session: 01a23519-e66f-7293-bb96-80091401c436 · slot 0 · generation 52

  • P2 pkg/frontend/table_dump.go:1790: Load the supplied v4.2.9 anonymous-CHECK archive into a missing table, truncate that table, and load the same archive again. Loading it into an empty CREATE TABLE LIKE copy also triggers the failure.
    Impact: The second load fails with error 20301, leaving the operator unable to restore the archive into the existing target. The target's reconstructed CREATE spells its generated CHECK name explicitly, but the release-schema matcher accepts this source-to-target name difference only for the old __mo_chk_N spelling. It therefore cannot establish the released binding era. Recognize a proven target-generated name while retaining full schema and binding verification and explicit-name controls.
    Evidence: The single-CN public probe in frozen-failing-probes.log first loads the unchanged v4.2.9 anonymous fixture successfully, then reproduces the failure both after TRUNCATE and on a CREATE TABLE LIKE copy. The retained catalog CREATE after TRUNCATE contains CONSTRAINT restored_chk_1, while the archived declaration is anonymous. Receipt 1796194191705066613-3.json records the failing probe against the frozen head.

  • P2 pkg/sql/plan/build_ddl.go:4542: Dump a table with an anonymous CHECK, then load it into a missing table named dst in a database where another table owns an explicitly named CHECK dst_chk_1.
    Impact: Automatic target creation fails with error 3822 even though the incoming CHECK is anonymous and could receive another generated name. The allocator checks names in the incoming definition but not the schema-wide CHECK namespace enforced at execution. Choose an available generated name using that namespace's existing admission rules, and retain its archive alias for fingerprint verification.
    Evidence: The public probe in frozen-failing-probes.log reproduces the collision while the same archive restores under a nonconflicting target name. The control in frozen-focused-tests.log verifies that the failed load leaves no target and that loading dst succeeds after the unrelated constraint is removed. Receipts 1796194191705066613-3.json and 1796194162224552072-3.json record those runs.

Validation:

  • The assigned private-runtime preflight passed. Source-fingerprinted focused Go tests passed for RANDOM_BYTES, historical binding recovery, CHECK-name and rename handling, index visibility, CN/TN metadata, frontend replay, and protobuf descriptors; see frozen-focused-tests.log and receipt 1796194162224552072-3.json.

  • Single-CN SQL probes restored the supplied v4.2.8 and v4.2.9 archives, checked stored values and later writes, and confirmed that a newly dumped invisible index remains invisible after restore.

  • Both reported counterexamples were reproduced through the public SQL path. Their expected failing run is retained in frozen-failing-probes.log with receipt 1796194191705066613-3.json.

  • The review audit verified the frozen head and clean source, 195 native inputs, five fixture manifests and six object checksums, and coverage of all 26 discussion keys. The required review plan and discussion assessment are saved in the diagnostic directory.

Limitations:

  • The full distributed BVT suite, multi-CN workload, race run, performance measurements, and physical stopped-upgrade exercises reported by the author were not independently repeated.

  • Fixture checksums were verified, but the claimed release-binary provenance was not independently established.

@XuPeng-SH

XuPeng-SH commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 724a45c6bf7c4f4dc60f3f7757a8b65893a7cbee

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Commit: 724a45c6bf7c4f4dc60f3f7757a8b65893a7cbee

Assessment: approve

The two restore defects reported on the preceding revision are addressed and passed public SQL probes on this head. The change reuses the existing volatility and vector mechanisms; the added CHECK provenance, aliasing, and binding verification support released archives and missing-target restore. No actionable unresolved findings remain.

Model: gpt-6.1-terra / max

Session: 01a2350e-851d-7031-94fc-615272373c71 · slot 2 · generation 20

Validation:

  • Private-runtime preflight, native-input provenance, and git diff --check passed.

  • Focused RANDOM_BYTES, planner, frontend, CHECK-name admission, and released-binding tests passed. See focused-unit.log and focused-controls.log, with receipts checks/1796200742542735341-3.json and checks/1796200558500008233-3.json.

  • Single-CN SQL probes passed the preceding collision and anonymous-archive reload reproductions, a collision-induced name round trip, and the newly added released-archive scenarios. See check-roundtrip-corrected.log and released-latest-cases.log, with receipts checks/1796200900544323601-3.json and checks/1796201095692910536-3.json.

  • Five fixture manifests and six object sizes and SHA-256 hashes matched. The review plan and discussion assessment are present; the assessment covers all 28 discussion keys exactly once.

Limitations:

  • The exact mo-tester case, full distributed suite, race run, multi-CN workload, performance benchmarks, and physical binary upgrade were not independently repeated. The supplied local_validation contains no receipts for the author's reported runs.

  • The first combined test run exited 1 because LOAD rejected targets after DELETE even though SQL reported zero visible rows. The same Rows-based emptiness guard is present in the base; the behavior was retained as a pre-existing limitation and characterized in focused-controls.log.

  • The first round-trip probe attempted DUMP with an in-memory row and failed its fixture precondition; the corrected probe passed.

  • Fixture checksums were verified, but the claimed release-binary provenance and current hotfix inventory were not independently verified.

This branch was successfully deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants