Repository navigation
fix(frontend): reject table-level publications whose views omit required relations - #30687
Conversation
…red relations A table-level CREATE PUBLICATION accepted a view whose base tables were not part of the published table list: publication and subscription creation both succeeded, but the subscriber resolves every relation of the persisted view SQL inside the publication's restricted table list, so every query of the subscribed view failed with `table ... does not exist` and SHOW CREATE VIEW kept displaying a definition that could never execute. The published object was unusable by construction. Root cause: the CREATE/ALTER path (genPubTablesStr) only proved that each requested name appeared in SHOW TABLES. It did not distinguish a view from a base table, did not expand the selected view's dependency closure against the requested scope, and never proved the stored definition executable inside that scope before writing mo_pubs/mo_subs. Change: add one shared explicit-scope validator (pkg/frontend/publication_view_scope.go) invoked for CREATE PUBLICATION, ALTER PUBLICATION (explicit and inherited table lists, including a source database change that omits TABLE) and subscription creation: - derive the full transitive relation closure of every selected view and reject irreducible omissions before any publication/subscription catalog write, with stable errors naming the view and the missing relation (for example `table-level publication for database 'view_pub_db' must include table 'base' required by view 'v_only'`); intermediate views are followed, CTE names and aliases are kept apart from catalog relations, and dependencies on another account's database, another subscription or a snapshot are rejected rather than silently included; rejected DDL leaves no publication or subscription residue; - after the name walk, re-bind each selected view through its stored definition inside the publication transaction and the source account's identity - the exact persisted-view binding a subscriber's first query performs - so a schema that no longer matches the stored definition is rejected before the catalog write; the relation snapshot and each probe are separate statements, so relations are re-read and compared by rel_id, rel_version, relkind and definition and a scope that changed underneath validation revalidates and fails closed after bounded attempts; - the probe is a pure metadata binding (defines.PublicationViewBinding): identifiers keep their source case (the probe parses at lower_case_table_names=0 and session temporary tables stay out of name resolution), the compile stops after binding, and the optimizer's eager-evaluation sites are gated under the marker (constant folding, LIMIT/OFFSET folding, window frame-bound evaluation, pipeline construction, and the geometry SRID safety walk whose deterministic-builtin admission now rejects any registration containing the internal-machinery class bit, plain or combined, so the probe can never execute internal UDF machinery through the direct-call builtin path), and user-defined function binding is refused with the stable subscription-resolution error; - subscription creation validates the final effective scope against the account that physically owns the published database, subscription metadata consumers resolve the physical source account consistently, CREATE DATABASE ... FROM re-checks the scope at subscribe time through the same validator, and snapshot/PITR restore replay passes the background session's case mode through the shared validation path; - the scope walker shares the remap-db statement walker through new dependency-collection hooks (CTE scope registration, CTE reference collection, per-expression observation), keeping remapping behavior unchanged and giving dependency classification the binder's own CTE visibility. TESTS: - pkg/frontend/publication_view_scope_test.go: validator unit tests - direct/nested/join dependency closures, constant views, duplicate and missing relations, quoted and case-mode identifiers, foreign-account, cross-database and system-relation dependencies, malformed and unsupported definitions, redefinition and schema-change revalidation, error, cancellation and retry propagation, and no-write-on-reject. - pkg/frontend/back_exec_test.go, publication_subscription_test.go, authenticate_test.go: CREATE/ALTER/subscribe integration, final effective list and database-change forms, foreign-source rules. - pkg/sql/plan/publication_binding_marker_test.go and pkg/sql/plan/function/deterministic_foldable_test.go: the binding marker's metadata-only contract, the SRID safety-walk admission rules, the deterministic-foldable internal-bit rejection, and the zero-execution proofs (including the counting-fake UDF service). - test/distributed/cases/publication_subscription/pub_view_scope.sql with its inspected result: cross-account BVT covering view-only rejection without residue, complete-scope and database-level controls, nested views and two-base joins enforcing the same rule, and ALTER narrowing rejected with prior metadata preserved. Related to matrixorigin#27767
5e4ca34 to
8ed7b9d
Compare
…st scopes Fixes two regressions the UT coverage CI found in this PR's own diff: - Test_createPubByPitr (pkg/frontend): createPubByPitr/createPubs resolved publicationBackgroundLowerCaseTableNames for every replayed publication, so an account-level (DATABASE *) or whole-database (TABLE *) replay failed with "session variable lower_case_table_names is unavailable" on an executor unable to name one. That mode is only consumed by the explicit-table-list scope validation, which those shapes never run. The replay now resolves it lazily, behind the new publicationCreateValidatesTableScope predicate that mirrors the exact shape createPublication validates. - TestCorrelatedLocalCTEPreservationProofDepth (pkg/sql/plan): the publication binding marker gate at aggregateSpineOriginalEmpty called builder.GetContext() unconditionally, panicking on a QueryBuilder built for a pure structural walk (nil compCtx). The gate now consults the marker only through a non-nil compilation context, restoring the function's pre-marker tolerance of direct construction. New focused tests pin both properties: TestPublicationCreateValidatesTableScope (shape truth table), Test_createPubByPitrTableScopeModeResolution (a table-list replay refuses an executor that cannot name its mode; the account-level replay above pins that nothing else consults it), TestPublicationBackgroundLowerCaseTableNamesResolution (back session names the registered default mode; a fake executor is refused). Proven with the repo cgo build env, go1.27.1: - go test ./pkg/frontend/ -count=1 -> ok 18.007s - go test ./pkg/sql/plan/ -count=1 -> ok 222.958s Related to matrixorigin#27767
The multi-CN compose BVT failed 11 statements of this PR's new
pub_view_scope case file, all downstream of one deterministic defect,
reproduced on a single CN with the same 883/872/11 vector:
create publication p_fsrc database fsrc2_db table base,v_x account vw02,vw03;
ERROR 1146 (HY000): internal error: table 'base' not exists
createPublication and alterPublication prove every explicit table list
through resolvePubTableNames -> showTablesFromDb, which runs
`show tables from <db>` on the DDL statement's background executor. For a
foreign-source publication, resolvePublicationDatabaseByName stamps that
executor to the source database owner's account for the catalog read, but
with the cluster protocol at or above 41 and no internal-executor marker,
the SHOW TABLES plan also appends the session-role metadata-visibility
fragment (sysview.MetadataVisibilityCTE, plan/build_show.go): it filters
rows by the DDL session's current_account_id() and active-role closure,
which never contain another account's objects, so the SHOW returned no
rows and every foreign-source table list failed with the false
"table not exists" error.
The read is DDL-internal and already admission-checked; it joins the
trusted internal discovery class that the plan already exempts from
role-visibility filtering (bootstrap discovery, snapshot/restore reads),
pinned by TestShowTablesBeforePrivilegeCatalogs. showTablesFromDb now
executes its SHOW with defines.AttachInternalExecutor (a new helper next
to IsInternalExecutor), preserving the SHOW's raw owner-account clause
while dropping only the session-role visibility fragment for that
internal read. User-issued SHOW TABLES keeps the visibility gate, and the
two remaining SHOW helpers only ever list mo_catalog, which the fragment
keeps universally visible - they are unchanged.
Proof (isolated single-CN cluster, macOS arm64, repo cgo build env):
- exact generated SHOW SQL on a live cluster: empty result under the sys
session over the owner's database, the owner's rows under the owner's
own session, the owner's rows without the visibility fragment;
- standalone repro, sys publishing vt1's database with a table list:
fails with the false "table 'base' not exists" before this change on
the PR head, succeeds and writes its mo_pubs row after;
- new UT Test_showTablesFromDbExecutesAsInternalDiscovery pins the
marker; go test ./pkg/frontend/ -count=1 returns ok;
- mo-tester pub_view_scope suite: 872/883 before, 883/883 after this
change on a fresh catalog, 883/883 again on the reused catalog.
Related to matrixorigin#27767
The mo-bot-local review of this PR proved an executable counterexample against the probe's metadata-only contract: llm_chat is registered STRICT without the internal-machinery class bit and without a volatile or real-time-related overload, so the guarded publication-binding fold's negative-only admission passed it and ConstantFold executed the LLM HTTP request while validating a publication's stored view definitions. GetFunctionIsDeterministicFoldableById is replaced by GetFunctionIsProvenPureFoldableById: nested function calls in the SRID argument tree are admitted only through provenPureValueFunctions, a closed curated list of pure in-process value transformations resolved through functionIdRegister at package init (an unresolvable name panics at init instead of silently weakening the gate). The previous negative predicates still compose in: no INTERNAL class bit, no volatile overload flag, no real-time-related overload flag. Every registration outside the curated set is rejected whatever its flags declare. Ordinary planning is unchanged: the ordinary post-bind fold switch keeps executing any unflagged builtin of a constant tree. The probe keeps its fail-closed verdict for unproven wrappers, the same divergence the internal-machinery veto already chose, while valid stored definitions (nested abs arithmetic) still fold to the same SRID literal. Tests: proven_pure_foldable_test.go replaces deterministic_foldable_test.go (closed-set exhaust ScanTest over the registry, review witnesses llm_chat/llm_embedding/try_starlark rejected on every overload, abs still admitted); the marker battery gains the review counterexample rebuilt on the deterministic in-process echo model - the marked probe rejects without executing where the pre-fix head bound SRID 4326 after evaluating the LLM machinery, and the ordinary bind still folds it.
|
mo-bot-local review follow-up — the P2 finding is fixed on head The counterexample was correct, and I reproduced it deterministically before fixing it. Fix, exactly along the recommended gate ("proven side-effect-free functions"):
Proof (repo cgo test wrapper in this worktree; logs preserved under the worktree
The residual trade-off is now explicit in the PR description: a future pure-but-unlisted builtin keeps failing closed in the probe until its registration is audited and added to the curated set — one line in one list behind an exhaustive regression test; ordinary planning semantics never depend on it. |
|
mo-bot review · Commit: "interrupted" |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 3b0b2fa9ebcb0125edb3e378102e29c5b48dfed1
Assessment: request_changes
Reviewed the complete 26-file delta and supplied comments. Shared admission validation and metadata-only binding are reasonable, and the earlier LLM side-effect finding is fixed. However, the new purity gate rejects valid constant-expression SRIDs.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
- P2
pkg/sql/plan/function/function.go:189: Publish a complete base-table/view scope where the view contains ST_GeomFromText('POINT(1 2)', CAST(IFF(1 = 1, 4326, 0) AS SIGNED) + 0). CREATE VIEW and ordinary stored-view binding succeed, but publication binding rejects the comparison inside the SRID expression because '=' is absent from the purity set.
Impact: Valid, queryable views are classified as broken, blocking explicit publication creation, widening ALTERs, and new subscriptions to existing publications. Preserve safe constant-expression compatibility by completing the audited purity classification and adding ordinary-versus-marked binding regression tests.
Evidence: Current-head TestReviewPublicationPureBuiltinsCreatedView reproduced the rejection for IFF/comparison, YEAR, JSON_EXTRACT and JSON_EXTRACT_STRING expressions. All four passed real CREATE VIEW planning and ordinary stored-view binding, then failed marked binding with 'the SRID argument of a geometry constructor must be a constant integer'; BIT_COUNT arithmetic passed both paths. Retained pure-builtins.log and checks/1792615571832878792-4.json record the assertion failures and exit 1.
Validation:
-
Artifacts are retained under /home/xupeng/.local/state/mo-bot/jobs/1244a7fcd5699032d9d1d42e/attempt-1. final-input-audit.json verifies the frozen head, clean source, complete supplied patch and diff --check.
-
Isolation preflight passed. Reused native artifacts only after verifying 192 matching native inputs and 46 artifact hashes; provenance is retained in native-reuse.json.
-
43 focused frontend tests passed: targeted-frontend.log and checks/1792615567300547306-5.json. Thirteen planner/function tests passed, including the retained LLM probe showing zero HTTP calls during marked binding: targeted-plan.log and checks/1792615432994566360-4.json.
-
validation-reconciliation.json correlates commands, source fingerprints, exits and logs, distinguishing confirmed regression failures from discarded exploratory cases.
-
The frozen CI snapshot reports successful build, Ubuntu UT, arm64 SCA, coverage and both multi-CN BVT lanes.
Limitations:
-
The regression reproduction uses production CREATE VIEW and stored-view planning with a mock catalog; no live SQL/BVT rerun was performed. Raw CI case logs were not supplied, and local_validation was empty.
-
No performance benchmark was run. Admission adds two database-wide metadata reads and per-view binding per stable attempt, with up to three attempts; subscription resolution adds source-owner catalog reads. Large catalogs and deep view chains remain unmeasured.
…iltins The guarded SRID fold of the publication-binding probe rejected valid stored definitions whose constant-expression SRIDs nest the plain SQL builtins the ordinary post-bind fold executes - a comparison inside IFF, a YEAR part extraction, and the JSON_EXTRACT/JSON_EXTRACT_STRING readers - because the curated provenPureValueFunctions set introduced to keep llm_chat out of metadata-only binding held only a small hand-picked list. The mo-bot-local review exported those four shapes as ordinary-versus-marked binding divergences that misclassified queryable, subscribable views as broken. Complete the set from a registry-wide audit instead: every writable SQL builtin whose overloads are clean and a deterministic in-process value transformation of its own argument vectors is admitted - comparison, logic, truth-value and membership predicates, bitwise operators, textual and pattern transforms, date/time parts and pure date arithmetic, JSON value-tree transforms, UUID and network-address transforms, geometry value functions, and the bitmap/hll/vector/ geo-cell scalars. The deliberate residue keeps its fail-closed rejection and is pinned as tests: environment and session readers, from_unixtime/convert_tz and random_bytes (clean-flagged, so membership is their only exclusion), the llm/starlark/jq interpreter family, fulltext match context readers, aggregates and window functions, and plan-internal helpers no persisted definition names. The publication marker battery grows the review's four shapes as ordinary-versus-marked agreement subtests, and the BVT suite gains the same four classes through publication, subscription, widening and re-subscription.
|
mo-bot-local review follow-up — the P2 finding is fixed on head The counterexample was correct, and I reproduced its four shapes deterministically on the previous head before fixing them; the ordinary bind folded each to SRID 4326 while the marked probe rejected with Fix, exactly along the recommended gate (completing the audited purity classification):
Proof (repo cgo test wrapper; logs preserved under the worktree
The residual trade-off stays the one already recorded in the PR description: a future pure-but-unlisted builtin keeps failing closed in the probe until audited into the set; ordinary planning semantics never depend on it. |
…sisted sort order The mirrored p_pure_new section of pub_view_scope.sql asserts the mo_catalog.mo_pubs residue after CREATE PUBLICATION. Its create-stage expected row was authored in the CREATE statement's declaration order (base_t,v_pure_if,v_pure_yr,v_pure_je,v_pure_js), but the DDL persists the resolved table list sorted (resolvePubTableNames applies slices.Sort before the join - a pre-existing upstream contract). The compose BVT on run 39682560695 (multi CN e2e BVT, COMPOSE/PESSIMISTIC) failed exactly there: 930/931 statements, the row-1534 residue query expected the declaration order while the engine answered the sorted base_t,v_pure_if,v_pure_je,v_pure_js,v_pure_yr. The same section's widening-ALTER row already recorded the sorted form and matched in the same run. Record the engine's deterministic sorted persistence in the create-stage row. Test expectation only - no engine, harness, or CI change. Validated on an exact-head clean instance (isolated single-process -launch cluster, SQL+HAKeeper/ISCP readiness, mo-tester method=run include=pub_view_scope): - pre-fix: 930/931 with the same single row-1534 mismatch, exit 1 (report/ci2-prefix-bvt.log) - post-fix: 931/931 twice consecutively on the same clean instance, exits 0 with teardown asserted after each run (report/ci2-postfix-bvt-1.log, report/ci2-postfix-bvt-2.log)
|
CI fix on head Failure — run 39682560695, attempt 1, head 930/931 statements of Expected Root cause — this PR's new fixture, not engine behavior. Fix (commit Proof (exact-head build — same native cgo recipe — of head
The fresh CI started by this push re-runs the compose/proxy lanes on the new head; the stale run 39682560695 was not rerun. The unrelated blocker record below (#30333 maven fetch, #27835 morpc GC race, #30231 CDC label-RPC stall) is unchanged. |
|
mo-bot review · Commit: Review completed. Read the assessment. |
|
mo-bot review · Commit: Review belongs to an older commit; it is not a review of the current head. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 868daa7417538bd199606c123460e8b8e3a6e71f
Assessment: approve
Reviewed the complete 26-file delta and relevant callers. The shared validator restores complete, bindable publication scopes while reusing the existing binder, preserving revocation and enforcing physical-source ownership. Both earlier review findings are addressed. No actionable unresolved findings remain.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
Validation:
-
Exact-head CI run 39693158951: native race-test stages and all eight planner shards completed successfully.
-
Multi-CN pessimistic BVT job 119546694328 verified the matching service build and passed pub_view_scope.sql: 931/931 cases, zero failures, ignored or abnormal cases.
-
Reviewed SQL oracles covering cross-account queries, failure residue, revocation, schema changes, case sensitivity, side effects and SRID compatibility.
-
Source remained clean; git diff --check passed. Commands, source fingerprints, exit receipts and retained logs were reconciled in /home/xupeng/.local/state/mo-bot/jobs/0abd601df79cb32ea19155d3/attempt-1/evidence-audit.json; detailed assessment is in review-notes.md alongside it.
Limitations:
-
Reused exact-head CI instead of repeating local native tests. Retained UT evidence provides stage checkpoints, not complete per-test JSON.
-
No base/head performance benchmark was available. Explicit-scope admission adds catalog snapshots and view binding; runtime subscription resolution adds an ownership lookup. These correctness costs were reviewed, but large-catalog performance is unmeasured.
Merge Queue Status
This pull request spent 2 hours 34 minutes 17 seconds in the queue, with no time running CI. ReasonThe merge conditions cannot be satisfied due to failing checks
HintYou may have to fix your CI before adding the pull request to the queue again. Waiting for any of
All conditions
Tick the box to put this pull request back in the merge queue (same as
|
What type of PR is this?
Which issue(s) this PR fixes:
Related to #27767
What this PR does / why we need it:
Problem
A table-level publication accepted a view as its only published object even when the view depended on an unpublished base table. Publication and subscription creation both succeeded,
SHOW CREATE VIEWreturned the definition, and then every query of the subscribed view failed:because the subscriber resolves every relation inside the persisted view SQL against the publication's restricted table list. The subscriber received a published object that was unusable by construction.
Publisher-side reproduction (matches the issue):
Root cause
The explicit table-list validation (
genPubTablesStrinpkg/frontend/publication_subscription.go) only proved that every requested name appeared inSHOW TABLES. It did not distinguish a view from a base table, did not expand the selected views' dependency closure against the requested scope, and never proved the stored definition executable inside that scope before writingmo_pubs/mo_subs. The subscriber resolver then enforces the restricted publication table list (InSubMetaTables) whilebindViewrecursively resolves the persisted view SQL, so the unpublished base relation failed to resolve at query time only.Exact change
One shared explicit-scope validator,
pkg/frontend/publication_view_scope.go(validatePublicationTableScope), invoked forCREATE PUBLICATION,ALTER PUBLICATION(explicit and inherited table lists, including a source-database change that omitsTABLE) and subscription creation, inside the publication transaction and the source account's identity, before any catalog write:table-level publication for database 'view_pub_db' must include table 'base' required by view 'v_only'. Rejected DDL leaves no publication/subscription residue.rel_id,rel_version,relkindand definition after the probe, so a definition that changed underneath validation revalidates the whole scope and fails closed after bounded attempts.defines.PublicationViewBindingmarker): identifiers keep source case (probe parses atlower_case_table_names=0; session temporary tables stay out of resolution), the compile stops after binding, the optimizer's eager-evaluation sites are gated under the marker (constant folding, LIMIT/OFFSET folding, window frame-bound evaluation, pipeline construction, and the geometry SRID constant-argument safety walk whose nested-builtin admission,GetFunctionIsProvenPureFoldableById, now admits only the function registry's positively proven side-effect-free pure-value builtins, rejecting everything else — internal machinery such as the python-UDF builtin through the class bit, and overtly effectful but clean-flagged registrations such as the LLM builtins through pure-set membership), and user-defined function binding is refused with the stable subscription-resolution error.Files:
pkg/defines/type.go,pkg/frontend/{publication_view_scope.go, publication_subscription.go, back_exec.go, authenticate.go, compiler_context.go, mysql_cmd_executor.go, remap_db.go, pitr.go, snapshot.go},pkg/sql/plan/{base_binder.go, build.go, flatten_subquery.go, function/function.go, limit_binder.go, mysql_special_types.go, window_binder.go}plus the test files below. No CI workflow files and no mo-tester changes.Issue-to-test proof
The rejected statement is the issue's exact fixture: post-fix,
TABLE v_onlyalone fails creation with the stable error above and leaves nomo_pubsrow and no subscriber database;TABLE base,v_onlysucceeds and the subscribed view answersCOUNT=2, SUM=30; the database-level control keeps its existing behavior (COUNT=2, SUM=30); a nested view chain and a two-base-table join enforce the same dependency rule (omitting either an intermediate view or a base table rejects);ALTERfrom a complete list to an incomplete list fails and preserves the prior publication metadata and the working subscription. The base-run failure of the unchanged fixture (publication + subscription created, every subscribed query failing with the missing-table error) is recorded with this issue's report.Test commands
Unit tests (with the repo's cgo build environment:
CGO_CFLAGS=-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include CGO_LDFLAGS=-L$(pwd)/cgo -L$(pwd)/thirdparties/install/lib GOEXPERIMENT=simd):All green locally (frontend package
ok, function packageok 12.109s, marker batteryok 1.727s).BVT:
test/distributed/cases/publication_subscription/pub_view_scope.sqlwith its result file (883 statements: account setup, the issue fixtures, complete-scope/database-level/constant-view controls, nested and join views, case-mode identifier variants, ALTER narrowing, residue checks, cleanup). It passes 883/883 statements against a locally built single-CN cluster on both a fresh and a reused catalog with the follow-up fix below in place; immediately before that fix it failed 11 of its own 883 statements on this PR's head, the same 872/883/11 vector the compose BVT CI reported. The sharedpublication_subscriptiondirectory shows only its pre-existing upstream drift (11 statements in 5 unrelated files, identical before and after this change).Residual risks
provenPureValueFunctions): a registration outside the curated set is rejected whatever its flags declare. An ordinary-quiet (NORMAL class, unflagged) but effectful builtin still folds in ordinary queries — that is ordinary planning semantics and stays untouched; the probe keeps it un-evaluated, and the definition decodes to its own non-constant verdict, the same fail-closed divergence already chosen for internal machinery. Growing the curated set requires auditing every overload of the named registration;proven_pure_foldable_test.gopins the closed-set property.publication_subscriptionfiles are pre-existing upstream drift at this base commit and are not touched by this PR.Follow-up CI fix (2026-10-21): scope resolution reads the source catalog as trusted internal discovery
The multi-CN compose BVT run failed 11 statements of the new
pub_view_scopesuite (multi cn e2e bvt test docker compose(PROXY), run 39525145416; the Coverage job failed downstream of it andCI Requiredaggregates both). All 11 traced to one deterministic defect, reproduced locally on a single CN with the identical 883/872/11 vector and error:Cause:
createPublicationandalterPublicationprove every explicit table list throughresolvePubTableNames->showTablesFromDb, ashow tables from <owner db>executed on the DDL statement's background executor. For a foreign-source publication,resolvePublicationDatabaseByNamestamps that executor to the source database owner's account for the catalog read; that executor carries no internal marker, so whenever the cluster protocol is at or above 41 the SHOW TABLES plan additionally appends the session-role metadata-visibility fragment (sysview.MetadataVisibilityCTEinplan/build_show.go). The fragment filters rows by the DDL session'scurrent_account_id()and active-role closure - the sys caller's - which never include another account's objects, so the SHOW returned no rows and every foreign-source table list failed with the false "table not exists" error.Fix: the read is DDL-internal, admission-checked, and already resolves the owner account itself, so it joins the trusted internal discovery class the plan already exempts from role-visibility filtering (bootstrap discovery, snapshot/restore reads;
TestShowTablesBeforePrivilegeCatalogspins that gate).showTablesFromDbnow runs its SHOW withdefines.AttachInternalExecutor(a new helper besideIsInternalExecutor), keeping the SHOW's raw owner-account clause and dropping only the session-role visibility fragment for that internal read. User-issued SHOW TABLES keeps the gate; the other two SHOW helpers in the frontend list onlymo_catalog, which the fragment keeps universally visible, and are unchanged. New UTTest_showTablesFromDbExecutesAsInternalDiscoverypins the marker.Proof (isolated single-CN cluster, repo cgo build environment):
buildShowTablesgenerates for a foreign owner's database returns no rows with the visibility fragment under the sys session, the owner's rows under the owner's session, and the owner's rows without the fragment;vt1's database with a table list: failed with the false "table not exists" error on this PR's head, succeeds and writes itsmo_pubsrow after the fix;go test ./pkg/frontend/ -count=1is green with the new UT;pub_view_scopesuite: 872/883 before, 883/883 after on a fresh catalog and 883/883 again on the reused catalog (the pre-fix local run is the recorded twin of CI's failure).Related to #27767
Base merge (2026-10-21, CI fix): adopt the upstream account-init protocol API
The
Connector/J Pool Reset E2Erun on the previous head failed at the build step. Apull_requestbuild compiles this branch merged against the currentmain, where upstream7038c8520e(information schema views metadata, #27716) had changedprotocolVersionForTenantInitializationfrom(service string) int64to(service string, proc *process.Process) (int64, error), so the new discovery file no longer compiled:Resolution (merge commit, upstream
774d0eda08..7038c8520e): mergemainto carry the new API, and adapt the single call inbuildPublicationProvisionedSystemRelations— the discovery passes the sessionless probe process (nil) to the two-argument helper; capability probes answer "unsupported" for a nil process, which selects the same conservative predecessor information_schema generationCREATE ACCOUNTitself falls back to, and an error keeps the minimum generation instead of broadening availability. The collected provisioned relation-name set is unchanged for every generation (below MORPCVersion126 each information_schema relation keeps its name, only its DDL body swaps), so both acceptance and rejection behavior are preserved. Shared files merged cleanly with both intents kept side by side (authenticate.go,authenticate_test.go,compiler_context.go,base_binder.go,mysql_special_types.go).Proof on the merged tree (repo cgo build environment):
CGO_CFLAGS=... go build -mod=readonly ./cmd/mo-service, succeeds (it failed with the exact errors above when the file still called the old signature);go test ./pkg/frontend/ -count=1isok, includingTest_showTablesFromDbExecutesAsInternalDiscovery,TestPublicationSystemRelationProvisionedForFutureAccountsand the validator battery (--- PASSfor 15 focused publication-scope tests);go test ./pkg/sql/plan/function/ -count=1isok 16.420s;go test ./pkg/sql/plan/ -run 'TestPublicationViewBindingMarkerPreservesConstantExpressionSRIDs' -count=1isok;go test ./pkg/sql/plan/ -count=1isok 69.691s.Related to #27767
Review follow-up (2026-10-22, mo-bot-local P2): gate the guarded SRID fold on positively proven side-effect-free builtins
The
mo-bot-localreview of headb6110b0a5bproved an executable counterexample against the metadata-only binding contract:llm_chatis registeredSTRICTwithout the internal-machinery class bit and without a volatile or real-time-related overload, so the negative-only admission passed it, andfoldGeometrySRIDConstArgexecuted it throughConstantFoldbefore the publication-binding marker's early return — publication and subscription admission issued the LLM HTTP request (the review's loopback probe observed exactly onePOST /api/chatwhile metadata binding returned nil). Absence of INTERNAL, volatile and real-time flags does not establish purity.Fix (function.go owns the gate; the walk keeps its shape):
pkg/sql/plan/function/function.go:GetFunctionIsDeterministicFoldableByIdis replaced byGetFunctionIsProvenPureFoldableById. Admission now requires membership inprovenPureValueFunctions, a closed, curated list of pure in-process value transformations (numeric canonicalization, pure textual transforms, constant branch selection), resolved throughfunctionIdRegisterat package init — a name that fails to resolve panics at init rather than silently weakening the gate. The previous negative predicates compose in: noINTERNALclass bit (tested through the bit viatestFlag), no volatile overload flag, no real-time-related overload flag. Every registration outside the set is rejected whatever its flags declare.pkg/sql/plan/mysql_special_types.go:isGeometrySRIDConstFoldSafeadmits nested functions only through that gate, so the probe still folds valid stored definitions (nestedabsarithmetic) to the same SRID literal, and a definition wrapping an unproven builtin keeps the ordinary non-constant verdict — the same fail-closed divergence the internal-machinery veto already chose. Ordinary planning is unchanged: the ordinary post-bind fold switch still executes any unflagged builtin of a constant tree.Proof (this worktree, repo cgo test wrapper; logs under
report/and the session record):st_geomfromtext('POINT(1 2)', cast(llm_chat('', '', 'echo', '', '[{"role":"user","content":"4326"}]') as signed) + 0). On the pre-fix head the marked probe bound it with SRID 4326 after evaluating the LLM machinery (recorded failure:An error is expected but got nil,report/review-2-prefix-failure.log); after the fix the marked probe rejects withthe SRID argument of a geometry constructor must be a constant integerand executes nothing, while the ordinary bind still folds it to SRID 4326 (publication_binding_marker_test.go, side-effect block subtests).proven_pure_foldable_test.go(replacingdeterministic_foldable_test.go) pins the gate: an exhaustive closed-set scan of the whole registry (every overload passes exactly through curated membership and clean flags; invalid overload ids never qualify), every curated name resolves to a non-internal registration with unflagged overloads, and the review witnesses (llm_chat,llm_embedding,try_starlark) — which carry none of the excluded flags — are rejected for every overload.go test ./pkg/sql/plan/function/ -count=1(full package) andgo test ./pkg/sql/plan/ -run 'TestPublicationViewBindingMarker' -count=1(whole marker family incl. the SRID battery) are green;gofmtandgo vetare clean.pub_view_scope.sql's SRID fixtures (4325 + 1,'4325' + 1,abs(4325) + 1, the rejectedabs(4326)root,1 + rand() * 0, the cast-root rejection) all keep their prior verdicts — no BVT shape ranges outside the curated pure set, and the compose/proxy BVT suites re-run on this head carry them through CI.Review follow-up 2 (2026-10-22, mo-bot-local P2): complete the proven-pure classification for ordinary SQL constant expressions
The
mo-bot-localreview of head3b0b2fa9ebreproduced the guarded SRID fold's remaining ordinary-SQL gaps:ST_GeomFromText('POINT(1 2)', CAST(IFF(1 = 1, 4326, 0) AS SIGNED) + 0)passes CREATE VIEW and ordinary stored-view binding, but publication binding rejected it because=inside IFF was absent from the curated purity set - and the same divergence for YEAR, JSON_EXTRACT and JSON_EXTRACT_STRING. Valid, queryable views were classified as broken, blocking explicit publication creation, widening ALTERs and new subscriptions.Fix - membership content only; the admission mechanism, its single caller (the guarded SRID walk
isGeometrySRIDConstFoldSafe) and ordinary planning are unchanged:provenPureValueFunctionsto every writable SQL builtin whose clean overloads are a deterministic in-process value transformation of its own argument vectors: comparison, logic, truth-value and membership predicates (=,<=>,and,istrue,in,like, ...), bitwise operators (&,|,^,<<,>>), the remaining textual and pattern transforms (binary,insert,regexp_*,to_base64,encode,decode,compress, ...), date/time coercions, calendar parts and pure date arithmetic (year,month,dayofweek,date_add,date_format,extract,interval,timediff, ...), JSON value-tree transforms (json_extract,json_extract_string,json_unquote,json_merge_patch, ...), UUID and network-address transforms, geometry value functions (st_/mbr constructors, readers and measurements), bitmap/hyperloglog/vector/s2/h3 scalar functions, andname_const.TestGetFunctionIsProvenPureFoldableByIdKeepsTheResidualExclusions): environment/session/build readers (charset,collation,current_*identity,validate_password_strength), the session-time-zone-dependentfrom_unixtime/convert_tzand the randomrandom_bytes- all clean-flagged, so curated membership alone keeps them out, the same property that excludedllm_chat; the program interpreters and service callers (llm_chat,llm_embedding,starlark,try_starlark,jq,try_jq); the fulltext match context readers; aggregates and window functions; plan-internal helpers no persisted definition names (serial/physical/to_interval machinery,__mo_json_*parameters, prefix-range predicates,values,assert,hash_value,mo_tuple_expr); and mixed-flag registrations that stay governed per overload by the existing flag predicates (format,week).Proof (repo cgo test wrapper in this worktree; logs under
report/in the session evidence):the SRID argument of a geometry constructor must be a constant integerwhile their ordinary leg passed (report/review-3-prefix-failure.log, exit 1); after the completed classification the same subtests pass both legs (report/review-3-postfix-four-subtests.log, exit 0).proven_pure_foldable_test.gogrows two pins:TestGetFunctionIsProvenPureFoldableByIdCompletesTheOrdinarySQLClassification(category representatives must keep every overload admissible) and the residual-exclusion taxonomy above; the previous pins stay (exhaustive registry scan: every overload's admission equals curated membership and clean flags; INTERNAL-class rejection across combined classes;llm_chat/llm_embedding/try_starlark/python-UDF rejection).go test ./pkg/sql/plan/function/ -count=1(full package) green; wholeTestPublicationViewBindingMarkerfamily including the SRID battery green; fullgo test ./pkg/sql/plan/ -count=1green; the focused frontend publication-scope battery green; gofmt and go vet clean.pub_view_scope.sqlgains a mirrored section for the four classes - the views publish, subscribe and re-subscribe answering SRID 4326 / WKTPOINT(1 2)equal to the literal twin, including a widening ALTER - and every existing rejection fixture keeps its verdict (cast root, abs root, rand subtree, and the side-effect definitions). The compose/proxy BVT suites re-run on this head through CI.Residual trade-off (unchanged in kind, now pinned by tests): a future pure-but-unlisted builtin keeps failing closed in the probe until its registration is audited into the set; ordinary planning semantics never depend on the classification.
CI follow-up (2026-10-22, compose BVT run 39682560695): the mirrored section's create-stage residue must record the DDL's persisted sort order
The
Matrixone Standlone CI execution / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)job on head304e08a5b5failed on exactly one of this PR's own new statements:The new section's create-stage expected row recorded the CREATE statement's declaration order (
base_t,v_pure_if,v_pure_yr,v_pure_je,v_pure_js), while the engine answers the persisted, sorted list (base_t,v_pure_if,v_pure_je,v_pure_js,v_pure_yr): the publication and subscription DDL persists the resolved table list sorted (resolvePubTableNamesappliesslices.Sortbefore the join — a pre-existing upstream contract this PR does not change, and the same resolved-list path the widening ALTER uses). The section's own widening-ALTER row already recorded the sorted form and matched in the same CI run; only the create-stage row was authored in declaration order.Fix (test expectation only, one line in
pub_view_scope.result): the create-stage expected row now records the engine's deterministic sorted persistence, consistent with the ALTER row. No engine, harness, or CI-workflow change.Proof (exact-head
mo-servicebuild of the head under test — same native cgo recipe as the prior rounds — launched as a clean, fully port-isolated single-process-launchcluster; readiness gated on SQL plus HAKeeper/ISCP startup evidence; mo-tester normal comparison modemethod=run include=pub_view_scope; logs under the sessionreport/record):[base_t,v_pure_if,v_pure_yr,v_pure_je,v_pure_js]expected vs[base_t,v_pure_if,v_pure_je,v_pure_js,v_pure_yr]actual, mo-tester exit 1 — byte-shape identical to the CI job's expected/actual (report/ci2-prefix-bvt.log; CI job excerptreport/ci2-composebvt-failure-excerpt.txt).DROP IF EXISTSrecovers no residue: teardown assertions after each run confirmmo_pubsp_pure%residue 0 and the fixture'svw01..vw05accounts and databases gone). Both runs exit 0 withSUCCESS RATE : 100%(report/ci2-postfix-bvt-1.log,report/ci2-postfix-bvt-2.log).