Skip to content

fix: preserve join predicate ownership during reordering - #30056

Merged
XuPeng-SH merged 82 commits into
matrixorigin:mainfrom
jiangxinmeng1:codex/fix-issue-29907
Oct 14, 2026
Merged

XuPeng-SH merged 82 commits into
matrixorigin:mainfrom
jiangxinmeng1:codex/fix-issue-29907

Conversation

@jiangxinmeng1

@jiangxinmeng1 jiangxinmeng1 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does / why we need it:

Fix issue #29907 by preserving join predicates that reference multiple join inputs during associative-law
rewriting.

Fixes #29907

Summary

  • Keep predicates that reference the moved join side on a join that owns all referenced relations during Rule 3 associative rewrites.
  • Prevent a mixed B/C predicate from being moved into the A/C join, which caused column remapping to lose dag.dag_id.
  • Add a planner regression test covering the exact Airflow query with and without USE INDEX (ti_state).

Validation

  • go test -mod=readonly -count=1 -timeout=180s -run "^TestIssue29907AirflowJoinColumnRemapping$" ./pkg/sql/plan
  • go test -mod=readonly -count=1 -timeout=12m ./pkg/sql/plan
  • git diff --check

XuPeng-SH and others added 30 commits August 5, 2026 21:43
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#26730

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

Planner fallback routing accepted the general `error` interface, but
INSERT,
LOAD, and DELETE assumed every binder error was a `*moerr.Error`.
Storage
cancellation, deadlines, and other ordinary Go errors could therefore
panic
while checking for `ErrUnsupportedDML`.

This change:

- uses the existing safe `moerr.IsMoErrCode` predicate at every affected
DML
  fallback boundary;
- preserves non-MO errors and wrapped cancellation errors without
converting
  or swallowing them;
- keeps the existing legacy fallback behavior for genuine
  `ErrUnsupportedDML`;
- adds a systematic matrix covering INSERT, LOAD, DELETE, UPDATE, and
REPLACE
against cancellation, deadline, plain, and wrapped errors, plus positive
  fallback controls.

Validation:

- `GOWORK=off go build -mod=readonly ./pkg/sql/plan`
- `GOWORK=off go vet -mod=readonly ./pkg/sql/plan`
- focused DML error propagation and fallback tests
- full `./pkg/sql/plan` test package via the repository CGo test wrapper
…rixorigin#26754)

MatrixOne transports prepared parameters internally through a transient text vector. That transport erased the source conversion semantics before assignment to `BIT(M)`, so the same value could be interpreted as ASCII bytes instead of a number.

This PR preserves the source conversion category across binary COM_STMT_EXECUTE, SQL EXECUTE USING, normal user-variable evaluation, process serialization, remote compile, and shard reads:

- signed and unsigned integers, including YEAR, use numeric BIT conversion;
- negative signed integers preserve their two-complement payload only for BIT(64);
- FLOAT/DOUBLE round with the existing numeric BIT rules;
- DECIMAL/NEWDECIMAL truncate the fractional part and keep exact uint64 range checks;
- Boolean values convert to 0/1;
- MYSQL_TYPE_BIT and string/blob parameters retain byte-string semantics;
- INSERT IGNORE retains the existing zero/max adjustment policy.

The metadata uses the existing process transport with backward decoding for legacy/no-metadata and the prior integer-only layout. Mixed-commit shard reads use the versioned method and are rejected before execution.

Approved by: @heni02, @XuPeng-SH
…igin#26842)

Backport the complete FileService range fan-out fix to `4.2-dev`.

`4.2-dev` contains the range-bypass and 200 ms fallback introduced by matrixorigin#24759
and matrixorigin#24871, but does not contain matrixorigin#26758. Therefore backporting only the
single-entry follow-up from matrixorigin#26834 would leave the multi-entry sparse-range
fan-out unchanged. This PR applies both fixes in dependency order:

1. matrixorigin#26758: avoid wide sparse fallback reads and bind waiters to the exact
cache-producing merge generation.
2. matrixorigin#26834: coalesce duplicate single-entry exact-range fallbacks after the
full-object generation exceeds its short wait.

The normal cache-hit and uncontended read paths are unchanged. All waits remain
caller-cancelable and bounded. Merge generations have no background goroutine
or persistent queue and are deleted on leader completion. Followers recheck
cache publication before falling back to a bounded exact read.

Validation on the `4.2-dev` base (`4066fffaf7`):

- focused FileService regression set, `-count=3`
- six concurrency/lifecycle tests under `-race` (`20` or `100` repetitions)
- full `pkg/fileservice` test
- full `pkg/fileservice` race test
- `go build` and `go vet` for `pkg/fileservice`

Backported commits retain `-x` provenance for matrixorigin#26758 and matrixorigin#26834.

Approved by: @XuPeng-SH
…ixorigin#26843)

Backport matrixorigin#26836 to `4.2-dev`.

matrixorigin#26042 fixed the original prepared-parameter identity problem. Later, matrixorigin#26531
added strict HashMap iterator row-range validation and incorrectly treated a
physical length-1 const vector as a flat vector. Prepared `GROUP BY ?` therefore
fails whenever the input batch contains more than one logical row.

This change preserves strict bounds for flat vectors while accepting non-empty
const and const-null vectors as broadcast inputs, matching the existing IntHashMap
and StrHashMap encoders. Zero-length const vectors are still rejected whenever
rows are requested.

Validation on the `4.2-dev` base (`4066fffaf7`):

- malformed-flat and const-broadcast regression tests, `-count=10`
- full `pkg/common/hashmap` test and race test
- `go build` and `go vet` for `pkg/common/hashmap`
- `validateIteratorVectors` coverage: `100%`

The cherry-picked commit retains `-x` provenance for matrixorigin#26836.

Approved by: @XuPeng-SH
…rigin#26868)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#25992

Follow-up to matrixorigin#26843 (the `4.2-dev` backport of matrixorigin#26836).

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

After matrixorigin#26843 accepts a physical length-1 const vector as a broadcast
input, a
prepared grouped query can correctly produce a projection batch whose
logical
row count is greater than its first vector's physical length:

```sql
SELECT ? AS projection_value, SUM(value_col) AS total
FROM metric_rows GROUP BY bucket ORDER BY total;
```

The frontend still derived result cardinality from
`bat.Vecs[0].Length()`.
Consequently, it emitted only one MySQL result row for a three-row batch
and
also undercounted `sentRows`. Saved query results had a second
inconsistency:
their metadata reported three rows, but object storage and `result_scan`
preserved only the first physical row.

This change uses `batch.RowCount()`, the logical cardinality propagated
by the
projection operator, for protocol output and row accounting. At the
query-result
persistence boundary, it validates vector shapes and creates an owned
writer
view only when compact const vectors need their logical lengths
normalized.
Aligned vectors are borrowed, mismatched const/const-null vectors remain
physically scalar, and the executor-owned input batch is never mutated.

Regression coverage includes flat, const, broadcast const, const-null,
malformed
and zero-row batches; allocation/write failure cleanup; real object
writer plus
`result_scan`; SQL-level prepared statement reuse; and the original
`GROUP BY ?`
path.

Validation on the exact `4.2-dev` base `9301a23cc8`:

- The direct-output BVT on the unfixed base: 19/21 statements pass; both
  parameter-first executions incorrectly return one row.
- On the direct-output-only candidate, `EXECUTE` returns 3 rows but the
immediate
  `result_scan(last_query_id())` returns 1 row.
- Focused frontend regressions, `-count=10`: pass.
- Full `pkg/frontend` test suite: pass.
- `go build -mod=readonly ./pkg/frontend`: pass.
- `go vet -mod=readonly ./pkg/frontend`: pass.
- `make build`: pass.
- Isolated single-node fixed candidate BVT, including saved scans for
first,
  NULL-reuse, and non-first parameters: 26/26 statements pass.
- MySQL binary `COM_STMT_PREPARE/EXECUTE` probe: parameter-first returns
3 rows,
NULL statement reuse returns 3 rows, and the matrixorigin#26843 grouped-parameter
control
  returns 1 row.

Direct output keeps an O(1) cardinality lookup. Saved aligned batches
allocate
nothing beyond the existing path. A mismatched const adds an O(column
count)
validation and copies only scalar physical storage; no per-row
materialization
or global object-writer contract change is introduced.
…igin#26894)

Backport matrixorigin#26774 to `4.2-dev`.

- Publish a new transaction snapshot only after the timestamp waiter succeeds, so cancellation and waiter errors cannot replace a valid snapshot with `0-0`.
- Propagate the statement context through disttae workspace writes, table lookup, dump, compaction, and duplicate checking instead of detaching catalog lookup with a background context.
- Return an ordinary invalid-input error when a transaction operation has no context deadline instead of terminating the CN process.
- Reject canceled delete operations before workspace mutation and cover the cancellation paths with regression tests.

The existing statement rollback contract remains responsible for undoing workspace changes when cancellation arrives after a statement has already started mutating its workspace.

This is a clean cherry-pick of commit `d68c9083e9411e55264bc54bc3b88fe1d079396a` from matrixorigin#26774 onto `4.2-dev` at `60283acdd464788cc0a1f91ad3e035dddc9454c4`.

Validation:

- `go list`, `go build`, and `go vet` for `pkg/txn/client`, `pkg/vm/engine/disttae`, `pkg/sql/colexec/deletion`, and `pkg/sql/compile`.
- Full tests for those four packages.
- Full race tests for `pkg/txn/client` and `pkg/vm/engine/disttae`.
- Four focused cancellation/snapshot regressions under the race detector, each repeated 100 times.
- `git diff --check` and pre-push concurrency/unhappy-path self-review.

Approved by: @XuPeng-SH
…trixorigin#26931)

Backports the MORPC fix that prevents an inconclusive control-probe timeout from resetting a data backend that can still return valid slow Lock responses.

The matrixorigin#26888 incident occurred on `4.2-dev`: one failed probe closed the shared backend and failed all pending Lock Futures together as ErrorCode 20505. The lock owner returned those responses shortly after the caller had already closed the connection.

This change affects only the response-inactivity path:

- seal the inactive data generation from new admission before probing;
- preserve its pending Futures when the independent control probe times out;
- direct new requests to the bounded replacement generation;
- retain immediate reset behavior for terminal data errors such as EOF, connection reset, and broken pipe.

The normal MORPC request/response path does not add locks, allocations, or RPCs.

### Backport verification

- Cherry-picked with `-x` from `aa11c18f2a3d6a2609eaa425ae50b51ce72c321f`.
- Backport and main commits have the same stable patch ID.
- No conflicts or manual semantic changes.
- Focused MORPC liveness/generation tests: `-count=30` passed.
- `TestTimedOutLivenessProbePreservesSlowDataResponse`: race `-count=100` passed.
- `go test ./pkg/common/morpc/...` passed.
- `go test -race ./pkg/common/morpc` passed.
- `go test ./pkg/lockservice/...` passed.
- MORPC and lockservice build and vet checks passed.

Approved by: @XuPeng-SH
…n#27095)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26960

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

Backport of matrixorigin#27043 to 4.2-dev.

Remote table-scan pipelines serialized the plan node, but the receiving
CN never restored Node.BlockFilterList into its execution Source. Remote
range expansion therefore received no block predicates and scanned the
full committed persisted partition.

This change:

- carries raw block-filter expressions in a per-message node copy
without mutating the reusable coordinator scope;
- folds session variables before serialization, then creates and
evaluates receiver-owned Fold executors on the remote CN;
- restores block filters for old-sender/new-receiver rolling upgrades;
- keeps decoded scopes as raw reusable templates and preserves empty
scalar literals across protobuf serialization.

Validation:

- GOWORK=off go build -mod=readonly ./pkg/sql/compile
- GOWORK=off go vet -mod=readonly ./pkg/sql/compile
- focused remote block-filter regression tests
- focused race stress for all three new tests with count=100
- full pkg/sql/compile tests, with and without the race detector

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

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26741

Related design discussion: matrixorigin#26775

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

Backport of matrixorigin#26918 to 4.2-dev.

Mixed DATETIME/TIMESTAMP comparisons previously cast the DATETIME
operand to TIMESTAMP. Predicates such as
system.statement_info.request_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)
therefore wrapped the column in a cast and prevented storage pruning
from seeing the raw DATETIME column.

This change keeps public result types unchanged and adds direct
cross-type comparison support for comparison operators and BETWEEN.
Column-to-runtime-constant predicates retain the raw column for pruning,
while non-constant operands are normalized to one physical TIMESTAMP key
domain for joins, shuffle keys, and runtime filters.

4.2-dev predates the zonemap helper refactor used by main, so the
backport implements the same timezone-aware, fail-open temporal matching
contract on the branch's existing zonemap API instead of pulling in
unrelated decimal-filter changes.

Validation:

- GOWORK=off go build -mod=readonly ./pkg/container/types
./pkg/sql/colexec ./pkg/sql/plan ./pkg/sql/plan/function
./pkg/vm/engine/readutil ./pkg/vm/engine/disttae
- GOWORK=off go vet -mod=readonly ./pkg/container/types
./pkg/sql/colexec ./pkg/sql/plan ./pkg/sql/plan/function
./pkg/vm/engine/readutil ./pkg/vm/engine/disttae
- focused DATETIME/TIMESTAMP comparison, binder, zonemap, and readutil
regression tests
- full owning-package tests for all six packages above

Co-authored-by: XuPeng-SH <[email protected]>
…in#27099)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26960

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

Backport of matrixorigin#26969 to 4.2-dev.

Table scans currently materialize every projected column before
evaluating residual filters. On the workload from matrixorigin#26960, the scan read
11.45 million rows / 7.32 GB and spent 62.78 seconds even though the
query returned no rows. The captured CPU profile was dominated by
copying and constructing varlen output rather than predicate evaluation.

This change adds block-local late materialization for output-only wide
varlen columns:

- predicate columns and fixed/small output columns are loaded first;
- visibility and tombstones are applied before the residual filter;
- surviving logical row positions are mapped back to physical block
offsets;
- deferred columns are loaded only for surviving rows.

The capability is optional on engine.Reader, so unsupported readers keep
the eager path. In-memory data, storage TopN, sharding readers,
transaction-data tracing, reader summaries, and unsupported expression
forms also remain eager.

4.2-dev predates the merge-reader ownership fix present on main. This
backport includes the required close-on-exhaustion/error behavior so the
new ReadWithFilter path has the same exactly-once reader cleanup
contract; focused tests cover both terminal paths.

Validation:

- GOWORK=off go build -mod=readonly ./pkg/vm/process
./pkg/sql/colexec/table_scan ./pkg/vm/engine/readutil
./pkg/vm/engine/tae/blockio ./pkg/vm/engine ./pkg/sql/compile
./pkg/vm/engine/disttae
- GOWORK=off go vet -mod=readonly over the same owning/dependent
packages
- focused late-materialization, row-mapping, reader-ownership, and
metric tests
- full owning/dependent package tests
- all eight focused tests with -race -count=100
- full process, table_scan, readutil, and blockio package tests with
-race

Co-authored-by: XuPeng-SH <[email protected]>
…origin#27003)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26991

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

This is the `4.2-dev` backport of matrixorigin#26998, adapted to the 4.2 tombstone
reader and on-disk layout.

Backup rewrites appendable TN tombstones after filtering rows by the
backup timestamp. The old rewrite path used a generic block writer,
which assigned dense seqnums to the physical `[rowid, pk, commitTS]`
batch. As a result, commitTS was persisted as ordinary seqnum `2`
instead of hidden `SEQNUM_COMMITTS`.

The v4.1 reader inferred that trailing column by position, so a v4.1.4
backup restored by v4.1.4 still works. The stricter 4.2 reader treats
commitTS as absent, synthesizes a const-null vector with no fixed
backing values, and could panic, reject recovery, silently omit
tombstones, or conservatively report false PK conflicts depending on the
consumer.

This PR closes both the producer and every identified reader boundary.

For newly generated backups, the trim path now produces one canonical
non-appendable TN tombstone layout:

```text
physical columns: [rowid, pk, commitTS]
seqnums:          [0, 1, SEQNUM_COMMITTS]
meta columns:     3
max seqnum:       1
```

The producer implementation:

- resolves commitTS, abort, and physical-rowid positions from source
object metadata;
- filters aborted rows and rows newer than the backup timestamp before
rewriting;
- drops the stale physical row address and the already-consumed abort
column;
- writes rewritten tombstones with explicit hidden-column seqnums;
- materializes a valid N-row constant commitTS before `BlockWriter`,
whose fixed-width metadata scan otherwise indexes beyond the one-value
backing;
- validates malformed source columns and releases rewritten batches on
success and error paths without double-freeing shared `objData`
references.

For existing malformed Backup artifacts, the reader implementation:

- recognizes only the exact non-CN, non-appendable three-column
signature (`meta_columns=3`, `max_seq=2`, `[Rowid, PK, TS]`, and no
strict hidden commitTS);
- reloads physical column `2` as commitTS while keeping a
timestamp-valued user PK distinct;
- validates commitTS at shared reader boundaries and returns bounded
errors for missing, null, wrong-type, length-mismatched, or
short-backing vectors;
- preserves valid non-null constant-vector broadcast semantics in point
lookup, block-mask evaluation, stats readers, local tombstone
application, PK-change checks, and TAE persisted scans;
- routes `persistedNode.Scan` and `CollectObjectTombstoneInRange`
through the compatibility mapping, while preserving the established
two-column CN tombstone `CreatedAt` semantics;
- releases the first cache lease and temporary vector wrappers before
compatibility reload, then transfers or releases the final
copy/zero-copy ownership exactly once;
- propagates an initial merge-stats iterator read error instead of
silently returning an undercount, while releasing previously admitted
iterators.

`4.2-dev` predates the shared `objectio.SpecialColumnLayout` and still
uses a reader layout without abort (`[rowid, commitTS]`, or `[rowid, pk,
commitTS]` when PK is requested). This backport preserves that 4.2
protocol and keeps an equivalent special-column resolver local to Backup
instead of pulling later appendable-object/abort reader changes into the
maintenance branch.

The fix is fileservice-backend independent, so DISK, DISK-V2, and S3
Backup rewrites use the same corrected metadata and reader paths.

Validation:

- deterministic old generic-writer artifact consumed through point
lookup, block mask, Backup datasource, varlen-PK search, TAE copy Scan,
zero-copy Scan, and range collection;
- CN-created two-column control proving Scan and range collection still
derive commitTS from object `CreatedAt`;
- timestamp-valued user-PK counterexample proving PK and trailing
commitTS remain distinct;
- exact compatibility-reload failure injection and non-legacy error
paths with cache-lease accounting;
- source layouts with commitTS only and physical rowid before/after
commitTS;
- abort metadata compatibility at the Backup rewrite boundary;
- future, aborted, partially retained, and fully filtered row sets;
- malformed/missing/short/null commitTS returns a bounded error;
- persisted and producer-side N-row constant commitTS broadcast
coverage, including `canonicalize -> WriteBatch -> Sync -> ReadDeletes`;
- merge-stats initial reader-error propagation;
- actual 4.2 checkpoint rewrite followed by metadata inspection and
`IsRowDeletedByLocation` verification;
- full tests for `pkg/objectio/ioutil`, `pkg/vm/engine/tae/logtail`,
`pkg/vm/engine/tae/tables`, `pkg/vm/engine/disttae`, and
`pkg/vm/engine/disttae/logtailreplay`;
- affected-package `go list`, build, vet, and scoped `golangci-lint` (0
issues).

---------

Co-authored-by: XuPeng-SH <[email protected]>
…atrixorigin#27129)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to matrixorigin#27124.

Backport of matrixorigin#26925, which fixes matrixorigin#26922.

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

### Root cause

When a remote Lock response is lost, canceled, or times out, the source
CN must retain the requested rows so transaction close can
conservatively send Unlock. In 4.2-dev those cleanup records are stored
in `activeTxn.tableKeys`, and distributed deadlock detection also treats
every entry in that collection as proof that the transaction holds the
row.

If the request is still waiting on the owner, the owner returns that
same transaction as a waiter and the polluted wait-for graph produces a
false `T <= T` self-cycle. This exact sequence is present in matrixorigin#27124: a
failed remote lock with `context canceled` is followed by a self-cycle
and user-visible `20701`.

### Fix

- Keep uncertain rows in `tableKeys` so conservative remote cleanup
remains unchanged.
- Track cleanup-only rows in a sparse per-table set and exclude them
from `fetchWhoWaitingMe`.
- Promote an uncertain row after a successful Lock result.
- Never downgrade an already confirmed row after a later uncertain
retry.
- Remove sparse state on lock removal, table cleanup, transaction close,
and object reuse.

This does not suppress genuine multi-transaction deadlocks. It removes
only deadlock edges that are not backed by a confirmed lock. Normal
successful Lock calls do not allocate the sparse state.

### Validation

- `TestRemoteWaitingListRequiresConfirmedHolder`: passed; race
`-count=100` passed.
- `TestCleanupOnlyLockStateTransitions`: passed; race `-count=100`
passed.
- `TestLockRemoteWithContextTimeoutTracksLockForUnlock`: passed; race
`-count=100` passed.
- `go build ./pkg/lockservice`: passed.
- `go vet ./pkg/lockservice`: passed.
- `go test ./pkg/lockservice`: passed.
- `go test -race ./pkg/lockservice`: passed.

Cherry-picked from `e88f5e4a706f28590f6dd69076cd38981eceaaa9`.

Co-authored-by: XuPeng-SH <[email protected]>
…atrixorigin#27167)

Backports matrixorigin#27166 (`f0d9a378ed`) to `4.2-dev`.

A replacement CN can publish a successful heartbeat and become visible to Proxy while its own local `MOCluster` still contains a pre-registration snapshot that does not include that CN. IVF entries scans require the current coordinator CN because only it can expose local appendable ranges, so this ordering gap can reject valid requests with `required-current-cn-outside-pool`.

This change gates CN startup before bootstrap and all query ingress until:

1. the first CN heartbeat succeeds;
2. an authoritative local cluster refresh succeeds; and
3. the refreshed snapshot contains this CN's service ID, pipeline address, and build commit.

The retry is bounded by the existing HAKeeper discovery timeout. Failure uses the existing CN startup rollback path. The change does not relax tenant/label pool isolation or IVF's `CurrentCNRequired` rule, and it adds no query or transaction hot-path work.

The original regression tests are included unchanged.

Approved by: @XuPeng-SH
…igin#27158)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26779

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

Backports matrixorigin#26782 (`c72224bea6`) to `4.2-dev`.

Adds a shared `ctl.GetFirstTNResponse` boundary for callers that require
a TN response. When no TN is available, table statistics, `SHOW
ACCOUNTS` storage usage, and `mo_ctl(..., INSPECT, ...)` now return
`ErrNoAvailableBackend` instead of indexing an empty result and
panicking the CN. Commands where an empty target set is valid continue
to consume `Result.Data` directly.

The original regression tests are included unchanged.

## Testing

- `go test -mod=readonly -count=1 -timeout 180s
./pkg/sql/plan/function/ctl ./pkg/frontend ./pkg/vm/engine/disttae`

Co-authored-by: aptend <[email protected]>
Co-authored-by: XuPeng-SH <[email protected]>
…xorigin#27222)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#27124

Backport of matrixorigin#27144. Related to matrixorigin#27142, matrixorigin#26925, and matrixorigin#26518.

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

### Root cause

matrixorigin#26518 moved synchronous IVF/full-text UPDATE maintenance to separate
top-level steps that consume a shared materialized final-row image. The
existing base/regular-index `LOCK_OP` remained downstream of that
materialization in only the main `MULTI_UPDATE` consumer.

The base consumer and hidden-index consumers could therefore acquire
locks in opposite order:

```text
T1: base row -> waits for IVF/full-text hidden row
T2: IVF/full-text hidden row -> waits for base row
```

matrixorigin#26925 removes false self-cycles from deadlock detection, but it cannot
remove these real two-transaction cycles.

### Fix

For UPDATEs with synchronous irregular-index maintenance, move the
existing base/regular-index `LOCK_OP` before the shared row-image
`SINK`:

```text
final row image
  -> existing LOCK_OP
  -> shared SINK
     -> base MULTI_UPDATE
     -> irregular delete maintenance
     -> irregular insert maintenance
```

Preserve the complete positional row image through the moved lock gate
so all sink consumers continue to resolve the same columns.

This is a semantic backport because the original main commit conflicts
with the current 4.2 planner implementation. It retains matrixorigin#27144's
lock-order invariant while adapting to the 4.2 UPDATE fanout helper. 4.2
does not support master-index UPDATE, so the regression covers its
reachable IVF and full-text paths.

### Risk assessment

- No new lock, lock mode, release rule, RPC, or lockservice behavior is
introduced.
- Normal UPDATEs keep `MULTI_UPDATE -> LOCK_OP`.
- Synchronous IVF/full-text UPDATEs execute the same lock operation
once, earlier in the same transaction.
- Async indexes remain CDC-only.

### Tests

- Verified the new planner regression fails on clean 4.2-dev
`aaac5956fd` for both IVF and full-text because the maintenance fanout
has no upstream base lock.
- `pkg/sql/plan` full package test.
- Focused planner regressions with `-count=10`.
- `go vet ./pkg/sql/plan`.
- `TestIssue26341CancelAndRetryFulltextUpdate` embedded three-CN
regression, covering lock blocking, cancellation, rollback, retry, and
hidden-index consistency.
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Refs matrixorigin#27287, matrixorigin#27288, matrixorigin#27289.

Backport of matrixorigin#27299 to `4.2-dev`.

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

- Makes the `information_schema.TABLE_CONSTRAINTS` tenant upgrade
converge when an older tenant contains a same-named base table.
- Stops the tenant-upgrade drain loop on errors or cancellation instead
of spinning indefinitely.
- Makes `DROP VIEW IF EXISTS` a no-op when the resolved object is a base
table, while preserving the error for `DROP VIEW` without `IF EXISTS`.
- Enables and updates the related BVT regressions.

This backport intentionally does not include the `v4_0_6` changes from
matrixorigin#27299 because those upgrade entries are not present on `4.2-dev`.

Validation:

- `make thirdparties`
- `GOWORK=off go list/build/vet/test` for `./pkg/bootstrap`,
`./pkg/bootstrap/versions/v4_0_5`, and `./pkg/sql/plan`
- Focused race tests, 100 repetitions each, plus full `./pkg/bootstrap`
race test
- `make build`
- `drop_if_exists.sql`: 47/47 passed, 0 ignored
- `alter_view.sql`: 100/100 passed, 0 ignored
fix: enable MongoDB external tables by default

Approved by: @fengttt, @XuPeng-SH, @aunjgr
The v4.0.6 tenant upgrade populates `information_schema.CHARACTER_SETS`, but a legacy tenant can be missing the table entirely. The population check then fails before the repair can run.

This backport:

- creates a missing `CHARACTER_SETS` table from the canonical DDL before population;
- leaves an existing table unchanged and keeps population idempotent;
- advances the v4.0.6 `VersionOffset` through the additional upgrade entry;
- backports the same-version offset execution rule already present on `main`, because `4.2-dev` would otherwise skip tenants already recorded at v4.0.6.

Validation:

- `make thirdparties`;
- focused missing/existing-table and same-version offset regressions;
- complete `pkg/bootstrap` and `pkg/bootstrap/versions/v4_0_6` tests;
- `go list`, `go build`, `go vet`, and `git diff --check` for both owning packages.

Approved by: @XuPeng-SH
…v of matrixorigin#27469] (matrixorigin#27479)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#27468

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

Ports the datastream external table (`CREATE EXTERNAL TABLE ... ENGINE =
DATASTREAM`)
to **4.2-dev**. This is a cherry-pick of matrixorigin#27469 (merged to main as
a826c02)
with the small adaptations 4.2-dev requires:

- `build_show_util.go`: 4.2-dev's SHOW CREATE does not thread `sqlMode`,
so
  `formatDataStreamTableOptionsForShowCreate` and its call site use the
no-`sqlMode` `formatStrInSingleQuotes` / `getRewriteSQLStmt` convention.
- filter deparser: 4.2-dev's `plan.Literal` has no `IsSerialized` field;
the
`IsBin` + printable + backslash guards still cover the unsafe-literal
cases.
- `plan.pb.go` / `pipeline.pb.go` / `mysql_sql.go` regenerated from the
merged
proto/grammar (adding the `DataStreamScan` message renumbers descriptor
  indices — mechanical, same as on main).

Feature summary (unchanged from matrixorigin#27469): a streaming gRPC data-load
bridge —
MO reads CSV chunks from a server described by `WITH
('server','port','table',
'recheck','apikey')`, reusing the CSV external scan operator via a
`DataStreamReader`; conservative filter pushdown (only under
`recheck=false`,
`''`-doubled quoting, backslash literals refused); optional API-key auth
with
an `env:NAME` reference that keeps the secret out of the catalog; and a
Java
reference server `xtool/jstfu` (jdbc + file sources, bounded/cancellable
streaming). See `docs/cn/stream_transport_fast_upload.md` and
`xtool/jstfu/README.md`.

Validated on this branch: full `go build ./...`, datastream unit tests
(parser, deparser, config/ResolveAPIKey, plan, frontend redaction), and
jstfu
Java build all green. BVT (`test/distributed/cases/datastream`) and the
e2e
harness (`test/datastream`) are carried over unchanged and run in CI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5 <[email protected]>
…n#27499)

Backport matrixorigin#27454 to 4.2-dev.

Release the temporary query-result metadata batch after object serialization completes. The writer stores serialized buffers rather than the input batch, so saveMeta retains ownership through every success and writer-error path and can safely clean it on return.

The source commit applied cleanly to the newest 4.2-dev tip.

Validation:

- full pkg/frontend suite

Approved by: @XuPeng-SH
## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#27404

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

Backport matrixorigin#27497 to 4.2-dev.

- Make live Go-heap-backed MPool ownership observable by global
bytes/objects metrics and per-pool diagnostics.
- Preserve the explicit-Free contract and strong pointer provenance,
including valid late Free after normal-pool deletion.
- Treat NoLock pool teardown as its terminal bulk-release boundary.
- Document the lifecycle contract and fix the test cleanup sites exposed
by the ownership audit.

The two source commits applied cleanly to the newest 4.2-dev tip.

Validation:

- full pkg/common/mpool
- full pkg/util/metric/v2
- full pkg/util/metric/mometric
- full pkg/frontend

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Prepared statements against `information_schema.TABLES` can return only a subset of the requested table names on 4.2 when the query contains a large parameterized `IN` list. For example, 132 existing names return only 2 rows, while the equivalent literal query returns all 132.

The composite primary-key predicate is folded into nested `OR` filters. A disjunctive `BasePKFilter` is a container whose zero-value `Op` happens to equal `function.EQUAL`. `mergeFilters` therefore treats two nested disjunction containers as atomic equality filters, compares their empty bounds, and drops the right-hand subtree.

This PR classifies disjunction containers before either connector enters the atomic merge path. `OR` can therefore flatten every branch, while `AND` conservatively keeps one safe atomic conjunct for early pruning and leaves the complete predicate to residual evaluation. The selected `AND` fallback also preserves its own OID when the container is the left operand.

Regression coverage includes `(((eq1 OR eq2) OR (eq3 OR eq4)) OR eq5)`, both operand orders for an atomic range combined with a disjunction, and a public SQL prepared-statement BVT covering both the mixed `AND`/`OR` predicate and the original `information_schema.TABLES` shape.

This is not a cherry-pick because there is no existing upstream PR that fixes this merge bug. The behavior first appeared with matrixorigin#25596. Main started returning the expected rows after matrixorigin#26627 added a cast to the hidden composite key and thereby stopped this query from taking PK pruning; the underlying nested-`OR` bug was not fixed. matrixorigin#27436 and matrixorigin#27448 were also tested on 4.2 and do not fix the failure.

Validation on latest `4.2-dev` (`63c24f9180`):

- SQL `PREPARE/EXECUTE`: requested/found = 1/1, 2/2, 5/5, 10/10, 20/20, 50/50, 132/132
- Go MySQL driver parameter binding: the same matrix passes, including 132/132
- Literal 132-name control query: 132/132
- Mixed range/disjunction prepared queries, in both operand orders: `a, z`
- `mo-tester` BVT `pk_filter_nested_boolean`: 29/29 statements, 100%
- `go test ./pkg/vm/engine/readutil -count=1`
- `go test -race ./pkg/vm/engine/readutil -run '^TestConstructBasePKFilterWithOr$' -count=10`
- `go vet ./pkg/vm/engine/readutil`
- `make build`

Approved by: @XuPeng-SH
…xorigin#27500)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#27406

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

Backport matrixorigin#27455 to 4.2-dev.

Keep ownership of the query-result metadata batch inside the builder
until every metadata field is appended. Any append error releases all
previously populated vectors before returning; a successful return
transfers the completed batch to its caller.

The production fix applied cleanly to the newest 4.2-dev tip. Its
regression test was placed into the older 4.2 test layout without
bringing unrelated main-only tests.

Validation:

- TestBuildQueryResultMetaBatchCleansPartialBatchOnAppendFailure
- full pkg/frontend suite

---------

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

Backports the explicit SQL ordering relation for scalar `FLOAT` and `DOUBLE`:

- ASC: `-Infinity < finite values < +Infinity < NaN`
- DESC: `+Infinity > finite values > -Infinity`, with NaN still last
- all NaN payloads are ordering peers, allowing later ORDER BY keys to break ties
- `-0` and `+0` are ordering peers
- NULL placement remains controlled independently by NULLS FIRST/LAST

The 4.2 full-sort, Top, MergeTop, MergeOrder, and window/range paths use this SQL relation. Generic comparison and storage sorting keep their existing contracts. Regular secondary indexes remain access paths for float keys, but cannot replace the logical sort or drive early LIMIT because their encoded NaN ordering is not SQL-equivalent.

Release-branch adaptation:

- `4.2-dev` does not contain main's PartitionTopN reducer/operator contract, so those two source/test files and their PartitionTopN-only window cases are intentionally omitted rather than resurrecting a removed subsystem.
- The 4.2 window operator receives only ORDER BY vectors after partitioning; the backport applies SQL ordering directly to that release-specific shape.
- 4.2 plan types do not carry the newer charset field, so MergeOrder preserves its existing type construction and changes only the comparator entry point.

Validation:

- full tests pass for `pkg/container/types`, `pkg/compare`, `pkg/partition`, `pkg/sort`, `pkg/sql/colexec/order`, `top`, `mergetop`, `mergeorder`, `window`, `aggexec`, and `pkg/sql/plan`
- affected packages pass `go build` and `go vet` against 4.2's locally built CGo/third-party artifacts
- `git diff --check` passes

(cherry picked from commit `99f4da5a092895fad6123a1862cf5e067e89a397`)

Approved by: @iamlinjunhong, @XuPeng-SH
…gin#27555)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Backport of matrixorigin#27528 for `4.2-dev`.

Related issue: matrixorigin#27523.

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

- Bounds Pipeline asynchronous backend-creation queue admission by the
configured per-connect timeout.
- Bounds the subsequent connect/retry phase by the same timeout, so a
stale scheduled CN route cannot inherit a potentially day-long SQL
context.
- Keeps the scheduled CN endpoint fixed: recovery establishes that route
within budget or fails the statement; it does not silently redirect work
to another CN.
- Adds a regression using the retryable RPC-timeout error produced by
the backend connect loop.

The backport patch-id is identical to the final two-file diff of matrixorigin#27528.

## Validation

- `GOWORK=off go list -mod=readonly ./pkg/cnservice/cnclient`
- `GOWORK=off go build -mod=readonly ./pkg/cnservice/cnclient`
- `GOWORK=off go vet -mod=readonly ./pkg/cnservice/cnclient`
- focused `TestPipelineBackendCreateOptionsBoundRetry`
- full `./pkg/cnservice/cnclient` tests
- focused race stress: `TestPipelineBackendCreateOptionsBoundRetry`,
`-race -count=100`
- full `./pkg/cnservice/cnclient` race test
- full `./pkg/common/morpc` tests
- full `./pkg/sql/compile` tests
- `git diff --check`
…in#27569)

After a TN failure produces an unknown commit, `unlockUnknownCommit` can retain `activeTxn.Lock` while deleting the transaction from its holder shard:

```text
activeTxn.Lock -> activeTxnHolder shard.Lock
```

At the same time stale-bind fencing in the affected 4.2 code retains `shard.RLock` while waiting for the transaction mutex:

```text
activeTxnHolder shard.RLock -> activeTxn.Lock
```

The bind-fence path also holds `bindChangeMu.Lock`, so the inversion blocks every later `service.Lock` request at `bindChangeMu.RLock`. Production goroutine profiles from matrixorigin#27562 contain both opposing stacks for the same five-minute interval and accumulating lock requests; restarting the affected CN clears the process-local deadlock.

This backport snapshots transaction keys under each holder shard, uses `TryLock` while the shard protects the pooled transaction pointer, and releases the shard before retrying a busy transaction. This lets unknown-commit deletion finish without changing normal Lock, Unlock, Commit, allocator-fence, or proxy semantics.

The cherry-pick applied cleanly to current `4.2-dev`; its patch-id is identical to the merged main fix.

Validation:

- `go build -mod=readonly ./pkg/lockservice`
- `go vet -mod=readonly ./pkg/lockservice`
- focused regression tests selected explicitly
- both focused regressions with `-race -count=100`
- complete `pkg/lockservice` test package
- complete `pkg/lockservice` test package with `-race`

Approved by: @XuPeng-SH
## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#25541

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

This is a bounded backport of the FULLTEXT2 behavior closure from the
fixed
`upstream/main` reference to `4.2-dev`. It keeps FULLTEXT2 distinct from
classic FULLTEXT and preserves the target branch's parser/PERFORM/pipe
contracts.

Source/target closure:

- source `upstream/main`: `8e616a693458652cc26b3c4be45c6602dff298d4`
- target `upstream/4.2-dev`: `d2393868a7aaa6343518d80849fe4696aa3577e9`
- exact fork head: `325686d29c17b3729f32b837b5bc2144d33f0a9b`
- matrixorigin#25904 core: `966acb2a92bb740e57b0b7a181df2d21956e1d3`,
`0eb9a921ece274c956447640b41ad2a255079e8d`,
`403a99fb65304e75b82e75793448f0690a871d0e`,
`bfa83f42737ca6304c0af3f6913e70ccc961464`
- matrixorigin#27165 phrase-position decode:
`2b142144c3c24a2100d7d313e952717025d56aeb`
- matrixorigin#27171 FT2-only wrapped score/range closure:
`835e046faa9242dbe288bd72364a475e2132bbed`
- matrixorigin#27461/matrixorigin#27462 cache and cold-load closure:
`e4abf5e90d0b5e09590571ca78447e50806527c`
- matrixorigin#27598 readiness BVT closure:
`e3a7440e2ac32bac780669f33c656960e22cff22`

Current-head review repairs:

- Reverse constant-left `<`/`<=` before harvesting a lower-bound MATCH
membership driver; reject constant-left `>`/`>=` upper bounds
fail-closed.
- Route all FULLTEXT2 ISCP consumer errors through the non-blocking
helper and
  report `ctx.Err()` on cancellation.
- Restore the execution-level `fulltext2_wrapped_score.sql/.result` BVT
pair
  and replace restore/clone fixed sleeps with readiness waits.
- Refresh the ancestor-accurate backport manifest and clear all
  `git diff --check` trailing whitespace findings.
- Trim FULLTEXT2 SHOW CREATE option padding only at the terminal output
  boundary, preserving the shared renderer and vector-index behavior.
- Route wrapped-only FULLTEXT2 score predicates on either INNER JOIN
child
through the existing wrapped rewrite and keep the score comparison in a
  post-rewrite FILTER.

## Validation

- `make -C pkg/sql/parsers/dialect/mysql` — PASS
- `make generate-pb` — PASS; protoc 29.3 descriptor-only churn was
discarded
  and no unexpected generated diff remains
- `go test -mod=readonly ./pkg/fulltext2/... ./pkg/iscp ./pkg/sql/plan`
— PASS
- current-head focused `GOWORK=off go test -mod=readonly -count=1
-timeout 120s -run '^TestFulltext2WrappedMatchJoinChild$'
./pkg/sql/plan` — PASS
- current-head `GOWORK=off go test -mod=readonly -count=1
./pkg/sql/plan` — PASS
- current-head `GOWORK=off go build -mod=readonly ./pkg/sql/plan` and
  `GOWORK=off go vet -mod=readonly ./pkg/sql/plan` — PASS
- current-head SCA repair — removed the unreferenced
`applyJoinFullTextIndices`
wrapper; targeted plan tests, build, and vet pass; exact-head remote SCA
is
  pending
- current-head focused SHOW CREATE regression and catalog option tests —
PASS
- local `mo-cgo-test` wrapper — BLOCKED by missing `cgo/libmo.dylib`; no
CGo
  wrapper pass is claimed
- `go test -race -mod=readonly ./pkg/fulltext2/... ./pkg/iscp` — PASS
- `go build -mod=readonly ./cmd/mo-service` — PASS (macOS linker
rpath/path
  warnings only)
- base differential — exact target
`d2393868a7aaa6343518d80849fe4696aa3577e9`
  rejects `CREATE FULLTEXT2 INDEX`; this exact head parses it as
  `INDEX_CATEGORY_FULLTEXT2`
- BVT source parity and no-fixed-sleep scan — PASS
- canonical wrapped-score BVT now covers wrapped-only MATCH on both
INNER JOIN
child positions with qualifying and rejecting thresholds; exact-head
remote
  BVT remains pending
- exact-head semantic preflight — `PASS semantic=PASS`, diff hash
  `efc51153938b14e051372026b296c06e05696385ac674fa7f05f3a7217741d09`

## Scope and acceptance boundaries

- `QA required: yes`
- The PR was opened as Draft for preflight and is now **Ready for
review**.
Required CI, formal reviews, and Mergify remain pending; no remote pass
is
  claimed until they bind to this exact head.
- Build success, index creation/readiness, and elapsed workload duration
are
  not acceptance by themselves. No classic FULLTEXT result, fixed-commit
  product acceptance claim, or formal QPS claim is used here.
- The 2.3M frozen corpus and shared `freetier-01` workload remain
post-merge
gates. After merge, only the official immutable image/release workflow
may
produce the tag/digest; `freetier-01` must be upgraded through the
reviewed
GitOps `environment=new-dev + mode=mo + action=set` PR. No local image,
direct `4.2-dev` push, direct GitOps edit, kubectl mutation, or pod
restart
  is authorized.
- The first post-release test is a unique-database 15-minute
small-corpus
FULLTEXT2 shakeout with readiness polling, token-bucket DML, C1/C10
readers,
  and an independent correctness ledger. Only `MEASURED_PASS` with zero
correctness errors, no backlog, and complete observations may unlock the
  low-load two-hour continuous run.

Please keep issue matrixorigin#25541 open until QA explicitly reports PASS/FAIL.

---------

Co-authored-by: Eric Lam <[email protected]>
Co-authored-by: XuPeng-SH <[email protected]>
## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#27740

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

Backport of matrixorigin#27747 to `4.2-dev`.

S3-compatible object stores can expose zero-byte folder marker objects
while
ETL merge scans a log directory. The merge task previously treated every
listed entry as a data file, so a marker without a `.csv` or `.tae`
extension
reached `newETLReader` and panicked the CN.

This change:

- filters directory and unsupported entries before adding them to an ETL
merge
  batch;
- dispatches readers by the exact final file extension;
- returns `ErrNotSupported` instead of panicking if an unsupported path
reaches
  `newETLReader`;
- adds deterministic regression coverage for zero-byte marker objects,
  directory entries, supported ETL files, and misleading suffixes.

The source patch applies cleanly to the latest `4.2-dev`, and its stable
patch-id matches matrixorigin#27747.

Validation on `4.2-dev`:

- focused `TestMergeMainSkipsNonETLEntries`, `TestIsETLFile`, and
  `Test_newETLReader` tests passed with non-empty selection;
- full `./pkg/util/export` package tests passed;
- `molint` passed for `./pkg/util/export`;
- `golangci-lint -c .golangci.yml ./pkg/util/export` passed with 0
issues.

BVT is not applicable because this changes only the internal ETL
background
file-selection contract and has no SQL-visible behavior.
…5114 (matrixorigin#27313)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#26720

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

Backport the fixes missing from `4.2-dev` for
[matrixorigin#26720](matrixorigin#26720) and
  [matrixorigin#25114](matrixorigin#25114).

  Included PRs:

  - matrixorigin#26711: Fix pipeline remote batch backpressure
  - matrixorigin#26739: Retry COS multipart initialization on EOF
  - matrixorigin#26759: Fix IVF prefilter OOM
  - matrixorigin#26989: Reduce IVF prefilter scan memory copies
  - matrixorigin#27156: Keep connections alive after long-running requests

The changes address vector-index memory usage, file-service retry
behavior, remote pipeline backpressure, and
  frontend connection lifecycle on `4.2-dev`.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: XuPeng-SH <[email protected]>
## What type of PR is this?

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

## Which issue(s) this PR fixes

Issue matrixorigin#27757.

## What this PR does / why we need it

- reuse the negotiated remote backend after a successful internal early
stop such as LIMIT completion
- keep query cancellation, query deadline, and substantive execution
failures terminal so their streams are poisoned rather than returned to
the pool
- backport main cancellation normalization semantics, including
`WithTimeoutCause` deadline classification and joined-error preservation
- publish `EventEnd` only for a successful internal early stop; publish
`EventError` for terminal cancellation/failure

No wire-format or timeout-default change is introduced. The normal
success path retains an immediate nil-error fast path.

## Validation

- `TestSuppressRemoteRunCancelError`: pass
- `TestIssue27757RemoteRunCancellationClassification`: pass
- each focused test under `-race -count=100`: pass
- full `pkg/sql/compile`: pass
- full `pkg/sql/compile` under `-race`: pass
- `go vet ./pkg/sql/compile`: pass
- `git diff --check`: pass

---------

Co-authored-by: XuPeng-SH <[email protected]>
… codex/fix-issue-29907

# Conflicts:
#	pkg/sql/plan/explain/sql_json.go
#	pkg/sql/plan/explain/sql_json_test.go

@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

placeholder

P2 - placeholder (test.txt:1)

placeholder

@XuPeng-SH

XuPeng-SH commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 2ca8ab065eb2d8b8a72ccd784ee81b4c07886e98

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: 2ca8ab065eb2d8b8a72ccd784ee81b4c07886e98

Assessment: approve

Reviewed the complete delta and affected optimizer callers. The guard restores predicate ownership within Rule 3 without changing execution or protocol contracts. The Airflow regression reaches the original column-remapping failure boundary. No actionable correctness defects remain.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

Validation:

  • Verified the frozen head, merge-base, clean checkout and matching patch; git diff --check passed. Receipt: checks/1791967655965854247-2.json; log: static-audit.log.

  • Isolation preflight passed. Dependency inspection confirmed the diagnostic requires no MatrixOne native libraries.

  • An isolated Go probe using unchanged production helpers and current protobuf types passed 256 predicate-reference combinations and eight destination controls. Predicates retained valid ownership without loss or duplication; the verified pre-fix sequence produced invalid ownership in 112 controls. Receipt: checks/1791967560387801159-2.json; log: ownership-probe.log.

  • Reviewed the committed parser-to-optimizer regression with and without USE INDEX. The frozen exact-head snapshot reports successful Ubuntu UT, coverage, SCA and Proxy/Pessimistic BVT checks.

  • Commands, source fingerprints, exits and retained logs are reconciled in /home/xupeng/.local/state/mo-bot/jobs/07fcee23b35654c513ec2d67/attempt-1/review-evidence.json.

Limitations:

  • The local diagnostic exercises predicate-transfer helpers, not the full optimizer or SQL service. local_validation is empty; author and CI per-test logs were unavailable.

  • Added tag-map construction and expression checks affect successful Rule 3 rewrites only. No comparative performance measurements were supplied or run.

  • The guarded reverse transfer is redundant for well-formed input joins; removing it is a nonblocking simplification opportunity.

@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

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

Deep review of exact head 2ca8ab065eb2d8b8a72ccd784ee81b4c07886e98 against merge-base a53390c57de48ac280249ff0e88831e502e20fb0, including the full two-file diff, optimizer callers and all existing review/discussion history. No blocking issue found.

Rule 3 must keep every predicate at a join that owns all referenced inputs. The added A/C containment check preserves mixed B/C predicates at the final join, without dropping/duplicating conditions or changing the failed-rewrite rollback and inner-join guards.

Independent exact-head validation in detached worktrees, using the repository CGO wrapper and provenance-checked primary native artifacts:

  • Full pkg/sql/plan: 3,708 root / 15,101 named passes, two existing skips; 16.077s.
  • The committed original Airflow query fails column remapping on the unchanged merge-base, with and without USE INDEX; both variants pass on this head.
  • 128 predicate-input/destination controls plus real parser/optimizer IN, COALESCE and OR shapes pass. An initial reduced-mock metadata error was corrected in the review-only fixture, not production.
  • Native single-CN SQL: ten fixed-result cases per round, two rounds, with/without ti_state, mixed predicates, duplicate join matches, NULL/filter exclusions and empty-result control; all pass (5.611s).

Required CI is successful on this head. The small native fixture does not assert forced Rule 3 selection; the statistics-controlled original planner regression and unchanged-base negative establish that boundary. No comparative performance or fresh-native-build claim. Head rechecked before submission.

@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 09:54 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-14 10:19 UTC · at 21bc20e654a6c1cf8e0015decb49d02bdc48fb75

This pull request spent 25 minutes 40 seconds in the queue, with no time running CI.

Reason

Pull request #30056 has been dequeued

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

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

Hint

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

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

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

  • Requeue this pull request

This branch was previously deployed

1 inactive deployment
ci — 21bc20e6 Deployed Oct 14, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Airflow TaskInstance/DagRun eager JOIN fails planner column remapping with and without index hints (v4.2.5)