Skip to content

fix: skip full file preload for readutil long scans - #102

Closed
LeftHandCold wants to merge 32 commits into
3.0-devfrom
fix/readutil-skip-full-preload-3.0-v2
Closed

LeftHandCold wants to merge 32 commits into
3.0-devfrom
fix/readutil-skip-full-preload-3.0-v2

Conversation

@LeftHandCold

Copy link
Copy Markdown
Owner

Summary

  • add SkipFullFilePreloads to readutil long-scan policy after readBlockCnt > threshHold
  • preserve existing SkipMemoryCacheWrites behavior
  • keep the fix scoped to the readutil caller; no fileservice global logic is changed
  • add a regression test for the long-scan policy bits

Root cause

Policy:2 only skipped memory-cache writes. For readutil long scans, the caller could still trigger full-object preloads into disk cache and OS page cache, amplifying range reads into full-file downloads. The missing caller flag is SkipFullFilePreloads; this PR only adds it on the existing long-scan threshold path.

Tests

  • go test ./pkg/vm/engine/readutil -count=1

LeftHandCold and others added 30 commits April 28, 2026 17:49
…gin#24196)

## 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#24183

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

Backport SQL syntax/operator compatibility fixes to 3.0-dev for issue
matrixorigin#24183.

This PR completes the 3.0-dev implementation of:
- MySQL JSON operators `->` and `->>`
- NULL-safe equal operator `<=>`
- multi-table `DROP TABLE`

During review, it also closes several correctness gaps needed to make
the backport safe on 3.0-dev:
- exact-vs-approx mixed numeric comparison fallback behavior
- JSON-to-numeric precision and overflow handling
- multi-drop privilege checks, FK-linked drops, and child-first drop
order handling

The change is implemented directly on 3.0-dev instead of cherry-picking
the main branch patches verbatim, because this branch already had
partial/incomplete wiring and diverges enough that a manual backport is
lower risk.

---------

Co-authored-by: Copilot <[email protected]>
…24214)

## 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#24189

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

This PR backports the user-visible time/date compatibility work needed
by 3.0-dev for matrixorigin#24189.

Main changes:

- Adds/ports MySQL-compatible temporal functions and parser support for
`CURTIME`/`CURRENT_TIME`, `TIMEDIFF`, `TIMESTAMPADD`, `TIMESTAMPDIFF`,
`GET_FORMAT`, `ADDTIME`, and `SUBTIME`.
- Aligns `DATE_ADD`/`DATE_SUB` string-input behavior and return typing
with MySQL-compatible runtime behavior.
- Fixes temporal overflow handling so large interval values fail safely
and return `NULL` instead of panicking or wrapping.
- Preserves time/date/datetime/timestamp scale and boundary behavior
through focused regressions and distributed expected results.
- Adds a LOAD DATA BVT that locks TIMESTAMP parsing to the session
`time_zone` used during import.

Validation performed:

- `go test ./pkg/container/types -run
'Test(JudgeIntervalNumOverflowRejectsMinInt64|DatetimeAddInterval|Datetime_ToTime|DatetimeAddIntervalOverflowReturnsFalse|DatetimeAddDateTimeOverflowReturnsFalse)'
-count=1`
- `go test ./pkg/sql/plan/function -run
'TestBuiltInCurrentTimeUsesSessionTimezoneAcrossDayBoundary|Test(DateStringAddReturnTypeCompatibility|DateStringSubDateFormatOutput|.*(TimestampAdd|TimestampDiff|AddTime|SubTime|GetFormat|TimeDiff|DateStringAdd|DateStringSub))'
-count=1`
- `go test ./pkg/sql/colexec/external -run 'Test_getColData_Timestamp'
-count=1`
- `SDKROOT=$(xcrun --show-sdk-path) CPATH="$SDKROOT/usr/include/c++/v1"
CPLUS_INCLUDE_PATH="$SDKROOT/usr/include/c++/v1" make build`
- Runtime SQL verified representative issue cases: `curtime`,
`timediff`, `timestampadd`, `timestampdiff`, `get_format`, `addtime`,
`subtime`, `date_add`, `date_sub`, scale casts, large-overflow `NULL`,
and LOAD DATA TIMESTAMP session timezone behavior.
- mo-tester targeted scopes passed with `FAILED :0`, `ABNORAML :0`,
`SUCCESS RATE : 100%`:
  - `test/distributed/cases/function/func_datetime_curtime.test`
  - `test/distributed/cases/function/func_datetime_addtime.test`
  - `test/distributed/cases/function/func_datetime_subtime.test`
  - `test/distributed/cases/function/func_datetime_timestampadd.test`
  - `test/distributed/cases/function/func_datetime_date_add.test`
  - `test/distributed/cases/load_data/load_data_timestamp_timezone.sql`

Note: this PR is scoped to the matrixorigin#24189 temporal compatibility surfaces.
An unrelated fulltext BVT issue was observed locally and is not changed
by this PR.

---------

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
…atrixorigin#24195)

## 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#24187

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

Support view-level privilege control with `GRANT/REVOKE ON VIEW` syntax,
including:

- Add `objectTypeView` to distinguish view privileges from table
privileges
- Support `DEFINER` and `INVOKER` security types for views via
`view_security_type` session variable
- Track view lineage (`viewChain`, `directView`) in plan nodes for
privilege checking at execution time
- Store `SecurityType` in view metadata (`ViewData`)
- Add distributed test cases for grant/revoke on view scenarios
…origin#24186) (matrixorigin#24191)

## 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#24186

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

Backports the prepared-statement / connector compatibility fixes from
`main` to `3.0-dev` listed in matrixorigin#24186:

| PR | Title |
|----|-------|
| matrixorigin#23413 | Fix BOOL MySQL protocol output and refresh BVT results |
| matrixorigin#23578 | Add `server_id` system variable for ODBC |
| matrixorigin#23864 | Reset vector class to FLAT in `ResetWithSameType` to fix
prepared stmt null json panic |
| matrixorigin#23887 | Fix NULL on duplicate key for unsigned columns *(already on
3.0-dev — skipped as empty)* |
| matrixorigin#23982 | Support JSON prepared params |
| matrixorigin#23984 | Clear prepared binary param state |
| matrixorigin#23980 | Harden prepare long data parsing |

#### Additional changes required to make the cherry-picks compile and
pass tests on 3.0-dev:

- Pulled in the prerequisite **matrixorigin#23978** *"harden prepared binary reset
cleanup"* (the COM_STMT_EXECUTE error path now returns the prepareStmt
so `clearBinaryParamState` runs; `doReset` now clears binary state;
COM_STMT_RESET / COM_STMT_CLOSE error paths return early instead of
dereferencing a nil prepareStmt; `parseStmtExecute` returns `preStmt` on
error).
- Added a missing `MultiUpdateCtx.clone()` helper (with `PartitionCols`
initialization) on 3.0-dev that matrixorigin#23980 expects.
- Adjusted the cherry-picked unit tests (`deletion_partition_test.go`,
`insert_partition_test.go`) to use the 2-argument
`testutil.MakeInt64Vector`/`MakeRowIdVector` signatures present on
3.0-dev, and renamed the partition `ExprWithRowID` field reference to
`Expr`.
- De-duplicated `TestResetWithSameTypeResetsClass` /
`TestFunctionResultAppendNullAfterToConst` (already present on 3.0-dev).
- Added support for DATE input under
`MYSQL_TYPE_DATETIME`/`MYSQL_TYPE_TIMESTAMP` in
`appendResultSetBinaryRow2` and brought scale/timezone-aware
DATE/DATETIME/TIME/TIMESTAMP formatting into `appendResultSetTextRow`
(matches `main`).
- A handful of refreshed BVT result files from matrixorigin#23413 were dropped
because the underlying BVT cases don't exist on 3.0-dev.

## Special notes for your reviewer:

CI on this branch will validate the BVT delta. Tested locally with `go
test -tags matrixone_test ./pkg/frontend/...
./pkg/sql/colexec/{insert,deletion,preinsert,multi_update}/...
./pkg/container/vector/...` — all green (with `TZ=UTC` for the
pre-existing TZ-sensitive `TestRowToString`).

---------

Co-authored-by: gouhongshen <[email protected]>
Co-authored-by: robll-v1 <[email protected]>
Co-authored-by: Cao Kai <[email protected]>
Co-authored-by: XuPeng-SH <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <[email protected]>
Backport block/mutex profiling startup flag support to `3.0-dev` so TKE regression YAML can pass the same profiling args used on `main`.

Changes:
- add `-block-profile-rate` to `mo-service` on `3.0-dev`
- add `-mutex-profile-fraction` to `mo-service` on `3.0-dev`
- enable block/mutex runtime profiling after flag parsing when the values are greater than zero
- include block/mutex profiles in periodic and shutdown profile dumps when enabled
- remove the previous unconditional block/mutex profiling setup from package init

Why:
- `mo-auto-test` now passes `-mutex-profile-fraction=100` and `-block-profile-rate=100` in `mo-bench-tke.yaml`
- old `3.0-dev` binaries reject these flags and crash DN with:
- `flag provided but not defined: -mutex-profile-fraction`
- this keeps `3.0-dev` compatible with the same annotation-driven profiling workflow as `main`

Validation:
- `git diff --check`
- `go test ./pkg/common/malloc/... -short`
- attempted `go test ./cmd/mo-service`, but local macOS environment is blocked by existing native dependency setup: missing `usearch.h` from `github.com/unum-cloud/usearch/golang`

Approved by: @XuPeng-SH
…rixorigin#24229)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#24227

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

Generalize the single-table scan filter rewrite into
`normalizeColumnDomain`
(`pkg/sql/plan/expr_opt.go`). For each column referenced by a scan's
`FilterList`, we now collect constant-domain predicates and merge them
into one
canonical expression:

- `col IN S1 AND col IN S2` → `col IN (S1 ∩ S2)`
- `col = v AND col IN S` → `col = v` (or `FALSE`)
- `col IN S1 AND col NOT IN S2` → `col IN (S1 \ S2)`
- `col IN S1 AND col <> v1 AND col <> v2 ...` → `col IN (S1 \ {v1, v2,
...})`
- `col IN S AND col IS NULL` → `FALSE`
- empty intersection / difference → `FALSE`
- outer `IN` domain is also propagated into OR branches and nested
`NOT(IN)`
so that `col IN S1 AND (col = 'x' OR col NOT IN S2)` collapses the inner
  `NOT IN` into `IN (S1 \ S2)` — the main bigsql scenario.

Preserves 3-valued logic: `NOT IN` / `<>` rewrites only kick in when
they sit
under an outer `col IN S`, since the outer `IN` already excludes NULL.
Lists containing NULL, non-constant lists, `BETWEEN`, and cross-column
predicates are left untouched.

UT: `pkg/sql/plan/filter_domain_test.go` covers
- IN + NOT IN → difference IN
- IN + multiple `<>` → difference IN
- empty IN intersection → FALSE
- IN + IS NULL → FALSE
- `=` + IN → single `=`
- IN × IN intersection
- NOT IN with NULL in list → untouched
- NOT IN inside OR branch → rewritten
- cross-column predicates → not merged

Local checks: `go test ./pkg/sql/plan/ -count=1`, `make`, `make
static-check`
all pass.

---------

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

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

## Which issue(s) this PR fixes:

issue matrixorigin#24249 

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

test: stabilize sql task cron case
…atrixorigin#24255)

## 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#24241

## What this PR does / why we need it:
- Cherry-pick of matrixorigin#24246 to 3.0-dev branch
- Add `UnpackNthElement` to deserialize only the Nth element from a
serialized tuple, avoiding full deserialization
- Add fast path in `serial_extract` for constant index parameter (the
common case in DISTINCT queries on secondary index)
- **7.9x speedup** on DISTINCT queries over composite secondary index
(14.9s → 1.9s aggregate phase on 5M rows)

## Adaptation for 3.0
- Removed `yearCode` case (not present in 3.0)
- Adapted nil test case (3.0 Packer has no `EncodeNull`)

## Test plan
- [x] Unit test `TestUnpackNthElement` passes
- [x] Local verification: 10M row table with 6-column composite index,
DISTINCT aggregate 1209ms (vs ~15s without fix)
- [x] Builds successfully on 3.0-dev

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

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: XuPeng-SH <[email protected]>
… filter domain before composite-key folding (matrixorigin#24261)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

issue matrixorigin#24227

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

Two independent changes on top of matrixorigin#24229:

### 1. `perf(plan)`: avoid proto text marshalling in hot paths

Large IN/OR queries (e.g. an outer IN with ~450 varchar values
combined with a nested `cast(col AS BIGINT) IN/NOT IN` list of
similar size) were spending ~95% CPU in
`proto.(*TextMarshaler).writeStruct`, driven by `Expr.String()`
being used as a map key inside `applyDistributivity` and inside
`constLiteralKey` (PR matrixorigin#24229). Both paths reflected over the full
expression tree on every call.

- `applyDistributivity` now uses a structural FNV-64 hash
  (`exprStructuralHash`) over the `Expr`'s ColRef / Literal /
  Function / List shapes, and falls back to a structural equality
  check only on hash collision. Right conjuncts are bucketed once
  so the left scan performs a single hash per cond.
- `constLiteralKey` packs the literal's proto **binary** form plus
  the Type fields directly into the key, avoiding the
  `TextMarshaler` in the per-literal hot loop of the domain
  rewrite.

**Measured on a BPC-style reproducer (MatrixOne container cluster,
10-core host, 19.5M-row scan):**

| Version | Query latency (steady) | CPU top |
|---------|-----------------------|---------|
| baseline (pre-PR) | 2.7 - 2.9 s | `proto.TextMarshaler` 96% |
| after `Marshal`-as-key | 2.9 - 3.2 s | `proto.ProtoSize` 56% |
| **this PR (structural hash + constLiteralKey fix)** | **0.52 s** |
`doPrefixIn` / `mallocgc` / `scanobject` (real work) |

### 2. `fix(plan)`: normalize filter domains before composite-key
folding

`optimizeFilters` used to run `mergeFiltersOnCompositeKey` before
`rewriteInDomainNotInFilters`. When the outer IN sits on the first
column of a composite primary key, the composite-key pass folds
that IN into `prefix_in(__mo_cpkey_col)` and the IN disappears
from the scan's FilterList. The domain normalizer then has no
outer IN to propagate, so nested `NOT IN` / `<>` / `cast(col)`
conjuncts (typically introduced by the binder when a varchar PK is
compared against an integer list) survive unrewritten. This
reproduces on BPC-style reports where the same column appears as
both an outer varchar IN and an inner `cast(col AS BIGINT)`
IN/NOT IN list — the exact scenario that motivated PR matrixorigin#24229.

Swapping the order lets the domain rewrite run against the
still-bare IN, collapse matching conjuncts into a single IN /
FALSE / equality, and only then hand the narrowed IN to the
composite-key folder (which gets a smaller point set for the
prefix_in seek).

The existing `in_domain` BVT cases on int primary keys now report
a single collapsed IN where they used to show two conjuncts; the
expected output is updated accordingly. Behavior on non-PK tables
is identical to before.

## Test plan

- [x] UT: `go test ./pkg/sql/plan/ -run TestRewriteInDomain -count=1` —
29/29 pass
- [x] BVT: `optimizer/in_domain` — 36/36 pass
- [x] `make && make static-check` clean
- [x] End-to-end check with the BPC reproducer — correct result, ~5×
latency improvement, pprof top now shows real data-path work

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
…in#24238)

Finishes YEARWEEK support on 3.0-dev after the latest temporal compatibility backport added the initial overloads.

`YEARWEEK(date[, mode])` is a standard MySQL function that returns year and week as YYYYWW format. This PR keeps the latest 3.0-dev scaffolding and fixes correctness gaps in mode handling:
- Reads non-constant mode values per row instead of using row 0 for all rows
- Propagates row-level NULL mode values as NULL
- Uses MySQL-compatible mode normalization (`mode & 7`) instead of clamping
- Covers date and string inputs for per-row mode / NULL mode behavior

Approved by: @ouyuanning, @aunjgr, @XuPeng-SH
matrixorigin#24239)

Re-implements WEEK() mode parameter support from main on 3.0-dev while preserving existing one-argument WEEK behavior.

MySQL's `WEEK(date, mode)` accepts an integer 0-7 as second argument to control week numbering semantics. Previously, MatrixOne's WEEK only registered single-argument overloads, causing `WEEK(date, 3)` to fail with "invalid argument function week, bad value [DATE BIGINT]".

This PR:
- Preserves the legacy one-argument `WEEK(date)` / `WEEK(datetime)` result path used by existing BVT cases
- Applies MySQL mode semantics only when the second mode argument is provided
- Registers `(T_date, T_int64)` and `(T_datetime, T_int64)` overloads
- Handles non-constant mode values and row-level NULL mode values correctly
- Adds coverage for the `2000-01-01` default WEEK case that failed BVT

Approved by: @ouyuanning, @aunjgr, @XuPeng-SH
…atrixorigin#24242)

Allows DATE_ADD/DATE_SUB interval operands to contain parenthesized modulo arithmetic before the time unit, such as:

```sql
DATE_SUB(CURRENT_DATE, INTERVAL (DAYOFWEEK(CURRENT_DATE) + 5) % 7 DAY)
DATE_SUB(CURRENT_DATE, INTERVAL (DAYOFWEEK(CURRENT_DATE) + 5) % 7 + 7 DAY)
```

The existing grammar already accepts the equivalent unary-plus expression form, so this PR narrowly normalizes `INTERVAL (expr) % ...` to that existing parse path without increasing yacc conflicts. It also keeps string/comment contents unchanged during normalization.

Approved by: @iamlinjunhong, @XuPeng-SH
…al expression (matrixorigin#24283)

- Add bounds checking in `resetDateFunctionArgs` and `resetIntervalFunctionArgs` to prevent index-out-of-range panic when the interval expression list has fewer than 2 elements
- This fixes a crash when using `INTERVAL` with non-constant expressions like column references (e.g., `'2024-01-01' + INTERVAL (result % 365) DAY FROM generate_series(1, 10) g`)
- Add unit test cases for interval expressions with column references

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

Approved by: @heni02, @aunjgr, @ouyuanning, @iamlinjunhong, @XuPeng-SH
This closes three related temporal compatibility gaps left after the earlier `WEEK` / `YEARWEEK` / `INTERVAL` fixes on `3.0-dev`.

- Make one-argument `WEEK(date)` / `WEEK(datetime)` read `@@default_week_format` at execution time, while keeping one-argument `YEARWEEK(...)` on MySQL\x27s fixed mode-0 behavior.
- Mark the one-argument `WEEK(...)` overloads as session-sensitive so they are not constant-folded with the wrong session default.
- Extend the MySQL lexer normalization so `INTERVAL (expr) DAY` works for `DATE_ADD` / `DATE_SUB` and `date +/- INTERVAL ...` forms, including nested-parenthesized expressions.
- Harden interval binder rewrites so malformed interval arg lists return an explicit error instead of panicking.
- Add regression coverage for the `WEEK` default-mode behavior, parenthesized `INTERVAL` operands, malformed interval arg safety, and the existing `interval(ts, 10, minute) sliding(...)` syntax so the lexer change does not overreach.

Approved by: @iamlinjunhong, @ouyuanning, @heni02, @XuPeng-SH, @aunjgr
…#24273)

This fixes the panic caused by reusing join result batches after an empty probe path.

When `emptyProbe` builds const output vectors, the next execution could reuse the same result batch with only `CleanOnlyData()`. That does not clear const vector state, so a later probe can append into a const vector and panic with `append to const vector`.

The PR now resets reused result vectors with `ResetWithSameType()` before writing probe results again. It also uses `vector.SetConstNull()` for empty-probe right-side NULL output, so reused vectors cannot retain stale data and accidentally become non-null constants after a previous non-empty probe.

Regression tests cover loopjoin / left / single join reuse in both directions: empty probe followed by non-empty probe, and non-empty probe followed by empty probe.

Approved by: @aunjgr, @XuPeng-SH
…4204)

This PR reimplements the MySQL type compatibility updates needed by `3.0-dev` for issue matrixorigin#24184 without cherry-picking the previous backport commits.

It adds or wires:

- YEAR type basics, parsing, planner mapping, vector function support, and cast execution paths.
- DECIMAL256 parsing/formatting, scientific notation with `e+NN`, planner literal typing, and string / NULL cast execution paths.
- MySQL SET value normalization/parsing and SHOW type formatting.
- GEOMETRY planner/type mapping and binary charset handling.
- Float overflow behavior for `exp()` and float addition.
- Focused unit tests for the new type and cast behavior.

Validation:

- `make`
- `make static-check`
- `go test ./pkg/container/types -count=1`
- `go test ./pkg/sql/plan -count=1`
- `go test ./pkg/sql/plan/function -count=1`
- `go test ./pkg/sql/parsers/dialect/mysql -count=1`
- `go test ./pkg/compare ./pkg/sort -count=1`
- `go test ./pkg/frontend -run 'Test.*Year|Test.*Geometry|Test.*Set|TestMysqlProtocol|Test_format|Test_getDataFromPipeline' -count=1`
- `go test ./pkg/vm/engine/tae/index -run 'Test.*ZM|Test.*Zone' -count=1`

Approved by: @heni02, @XuPeng-SH, @aunjgr, @iamlinjunhong
…#24311)

Fixes ObjectIO partial-read error paths that can drop `IOEntry.CachedData` without releasing it. When a FileService read fills some cache entries and then returns an error, for example after a LIMIT query cancels parallel table-scan workers, the read helper previously returned without releasing the partially-filled read results. Under cache eviction this can surface as a checked malloc `missing free` panic from `fileservice.Bytes` allocated through `DiskCache.Read -> objectio.constructorFactory`.

This PR:

- Adds `IOVector.ReleaseReadResultOnError()` to release cached data and raw read buffers only for completed entries, avoiding double-deallocation of an entry whose `ReadFromOSFile` already unwound its own failed raw buffer.
- Uses that cleanup in `ReadOneBlockWithMeta`, `ReadExtent`, `ReadAllBlocksWithMeta`, and `ReadOneBlockAllColumns` when `fs.Read` or post-read processing returns an error.
- Releases allocated decompression cache data if LZ4 decompression fails before ownership is returned.
- Adds unit coverage for partial-read cleanup, skipped failed-entry raw-buffer release, and decompression-error cleanup.

Approved by: @fengttt, @XuPeng-SH
Fixes the CN logtail consumer backlog risk found in nightly sysbench write-heavy regressions.

The bad run had `logtail.consumer.slow.*` in the `update_pk_1000` window, with `signal-chan-len` around 7373~7738 on one CN consumer routine. The good control run using the same MO image did not have these slow logs in the same case window. No sysbench reconnect/retry storm, workspace quota shortage, or UPDATE table-lock upgrade was found.

This PR reduces internal backpressure without changing table assignment or increasing consumer routine count:

- coalesces update-response timestamp commands for routines that already have table logtail commands,
- advances the routine applied timestamp only after that routine consumes the last table logtail for the response,
- keeps timestamp-only commands for routines that do not receive table logtails, preserving global min applied timestamp semantics,
- makes timestamp waiter commit-ts notifications non-blocking and coalesced to the latest timestamp,
- adds tests for non-blocking timestamp notifications, bounded notification draining, and logtail timestamp advancement ordering.

Approved by: @XuPeng-SH
Address matrixorigin#23965 by teaching the planner to reuse the physical order of non-unique regular secondary indexes for ORDER BY primary-key LIMIT queries when all non-PK key parts are fixed by equality filters.
Rewrite the sort anchor to the hidden serialized key, wire top-value messaging directly between sort and scan, and add focused planner tests for the optimized and non-optimized cases.

Approved by: @ouyuanning, @aunjgr, @XuPeng-SH
matrixorigin#24329)

support Hive-style partitioned Parquet external tables

Approved by: @heni02, @XuPeng-SH, @aunjgr, @fengttt
Backports and adapts the missing user-visible LOAD DATA / parquet compatibility fixes from main to 3.0-dev:

- supports LOAD DATA TIMESTAMP parsing with the session timezone coverage
- updates parquet-go and parquet mapping for basic/logical parquet types
- supports parquet binary DECIMAL loading, including FixedLenByteArray, with source-to-target scale rescaling and target precision validation
- treats AUTO_INCREMENT zero values consistently with MySQL sql_mode / NO_AUTO_VALUE_ON_ZERO in ingestion paths
- supports JSON -> JSON cast so LOAD DATA into JSON columns does not fail with unsupported cast
- updates related BVT coverage for load_data, auto_increment, fulltext, and snapshot cases

Validation:

- `go test ./pkg/sql/colexec/external -run 'Test(ReadFileOffsetCompressedUnsafe|_getColData_Timestamp|parquet|Parquet)' -count=1`
- `go test ./pkg/sql/colexec/preinsert -run 'Test(ShouldConvertZeroToNullSkipOnUpdate|ShouldTreatZeroAsAutoIncrFallback|PreInsert)' -count=1`
- `go test ./pkg/sql/plan/function -run 'TestCastJsonToJson|TestCastJson' -count=1`
- `go test ./pkg/frontend -run 'TestGetSqlModeNoAutoValueOnZero|TestEnableRemapHint' -count=1`

Approved by: @ouyuanning, @heni02, @aunjgr, @XuPeng-SH
…#24345)

This fixes the remote lock caller hang exposed by matrixorigin#24333 and follows up on matrixorigin#24206.

matrixorigin#24206 correctly tightened stale remote bind handling by moving remote keepalive and orphan cleanup to bind granularity, but it also changed remote lock and forward-lock responses from `AsyncWrite` to bounded synchronous `cs.Write`. When that bounded write fails, the old path only returned the error to the handler. The peer can then stay blocked in `remoteLockTable.lock -> client.Send -> Future.Get` because no response is delivered and the morpc session remains open.

This PR closes the lockservice RPC client session on any response write failure. That converts a local response-write failure into a deterministic peer-side connection error, so pending futures fail and the waiting transaction follows the existing rollback and unlock path instead of holding locks indefinitely.

I intentionally do not roll back remote lock state from the write-failure path itself. After a write or flush failure, response delivery is ambiguous; unilateral unlock on the server side is riskier because the caller may still observe success and continue without a valid remote lock.

Also included:
- richer remote lock write-failure logs with request id, method, remote endpoint, txn id, bind, caller service, and row count
- a regression test that verifies write failure closes the session while successful writes do not
- no `lock_wait_timeout` mitigation from matrixorigin#24340 in this PR

Approved by: @iamlinjunhong, @XuPeng-SH
matrixorigin#24347)

Backport of [matrixorigin#24313](matrixorigin#24313) (Branch Protect Snapshot) to `3.0-dev`.

Same motivation as main: after flush + global checkpoint + disk-cleaner GC,
the LCA probe in `data_branch_hashdiff.go` can silently downgrade an
`UPDATE` into an `INSERT` once GC reclaims the pre-branch object of the
probed row. This feature pins parent-side history for the exact duration
a branch subtree is alive.

### 3.0-dev adaptation

`mo_catalog.mo_snapshots` on 3.0-dev has no `kind` column, and adding one
would require a stable-branch schema migration. This backport identifies
branch-managed rows entirely by their synthesised sname prefix
`__mo_branch_<child_table_id>` (exposed as
`databranchutils.BranchSnapshotSnamePrefix`). Every user-facing filter
that on main reads `kind != 'branch'` is implemented here as
`sname NOT LIKE '__mo_branch_%'`. Functional behaviour and invariants
are identical to main.

### Lifecycle

| Phase | Trigger | Helper |
|------|---------|--------|
| Create | `DATA BRANCH CREATE TABLE/DATABASE` → `updateBranchMetaTable` | `createBranchProtectSnapshot` (atomic with the CLONE DDL and `mo_branch_metadata` insert) |
| Reclaim (frontend) | `DATA BRANCH DELETE TABLE/DATABASE` | `reclaimBranchSnapshotsWithBH` |
| Reclaim (ddl.go) | plain `DROP TABLE` / `DROP DATABASE` cascade | `(*Compile).reclaimBranchProtectSnapshots` (with a fast-path probe that skips the `FOR UPDATE` scan when the drop touches no branch row) |
| Shared core | subtree-alive predicate + cycle guard over `mo_branch_metadata` | `databranchutils.ReclaimBranchSnapshotsCore` |

### User surface

- `SHOW SNAPSHOTS` filters out sname prefix `__mo_branch_%`.
- `DROP SNAPSHOT __mo_branch_<tid>` is rejected with "managed by data branch".
- `SHOW RECOVERY WINDOW` / `SELECT ... {snapshot='__mo_branch_*'}` / `RESTORE SNAPSHOT __mo_branch_*` all reject via the central `getSnapshotByName` guard.
- Cross-account `DATA BRANCH CREATE ... TO ACCOUNT <b>` anchors the snapshot on the parent's account.

### Files intentionally omitted from the backport

These files exist on `main` but not on 3.0-dev, so there is nothing to patch:

- `pkg/frontend/check_snapshot_flushed.go` — its `GetSnapshotInfoByName` does not exist on 3.0-dev.
- `pkg/frontend/object_list.go` — the `{snapshot='...'}` resolver path on 3.0-dev goes through `getSnapshotByName` only.
- `pkg/frontend/feature_limit.go` — per-account snapshot quota feature is not in 3.0-dev.
- `pkg/vm/engine/test/branch_protect_snapshot_test.go` — the engine harness on 3.0-dev lacks the `exec_sql` helper used on main. Coverage is retained via the 10 BVT cases and 10 unit tests.

### Test coverage

**Unit tests (10/10 pass)** — `pkg/frontend/data_branch_snapshot_test.go`:
sname format, DAG builder, `subtreeAllDeleted` on linear / branching
DAGs, reclaim core drop-list, ancestor walk, dangling metadata, cycle
guard, drop rejection by sname prefix, SHOW SNAPSHOTS SQL predicate.

**BVT (10 cases, 194 queries, 3 consecutive 100% pass runs)** —
`test/distributed/cases/git4data/branch/protect/protect_1..10.{sql,result}`:

| Case | Coverage |
|-----|---------|
| 1 | Creation + visibility + SHOW filter + prefix-based kind bucket |
| 2 | Reclaim on `DATA BRANCH DELETE TABLE` |
| 3 | Reclaim on plain `DROP TABLE` |
| 4 | Subtree retention (linear chain) |
| 5 | Fan-out independence (three siblings) |
| 6 | SHOW SNAPSHOTS filter coexists with user snapshots |
| 7 | Same-account account-scoping |
| 8 | `DATA BRANCH CREATE/DELETE DATABASE` batch create+reclaim |
| 9 | Plain `DROP DATABASE` cascade reclaim |
| 10 | Full cross-account `TO ACCOUNT <b>` round-trip |

**GC → diff regression (3/3 pass, 59 queries)** —
`test/distributed/cases/git4data/branch/diff/diff_9.sql` is tightened
with a pre-branch PK update assertion (the exact shape of the original
bug): after GC the diff must still classify as `t1 UPDATE` not
`t1 INSERT`.

Approved by: @fengttt, @heni02, @XuPeng-SH, @ouyuanning
…atrixorigin#24353)

Ports the `cast_geometry_to_subtype` runtime function from `main` to `3.0-dev` so that INSERT/UPDATE operations validate the WKT geometry subtype and SRID against the column declaration. Previously on `3.0-dev`, a column declared as `POINT` could silently accept a `LINESTRING` value.

### Changes:
- Register `CAST_GEOMETRY_TO_SUBTYPE` function ID and built-in overload
- Implement `CastGeometryToSubtype` runtime function with full WKT structure validation
- Add `funcCastForGeometryType` planner function that wraps geometry expressions with subtype/SRID validation
- Wire geometry cast into all INSERT/UPDATE bind paths (bind_insert, bind_update, build_update, build_constraint_util, make.go)
- Add unit tests covering subtype match/reject, SRID mismatch, malformed structure, and non-finite coordinates
- Add `T_geometry` support to the function test framework

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

Approved by: @XuPeng-SH, @aunjgr
…faults (matrixorigin#24337)

Under IOChaos filesystem error injection, WriteTransferPage fails silently and still sets invalid paths on pages. The flusher keeps scheduling new flush tasks causing a 93 GB cumulative allocation storm that OOMs DN in 2 minutes.

Changes:
1. Bounded retry with backoff (3 attempts, 100ms/200ms/400ms)
2. Error propagation - paths only set on success
3. Graceful degradation - pages kept in-memory on write failure

Approved by: @XuPeng-SH, @aunjgr, @aptend, @heni02, @ouyuanning
….0-dev (matrixorigin#24342)

PR matrixorigin#24204 added plan/type-level support for YEAR / DECIMAL256 / SET on `3.0-dev`, but did not touch the vector container, the TAE compute/index layer, or the frontend codec paths. Heni02's latest comment on matrixorigin#24184 reproduces three failures caused by those gaps:

- `INSERT INTO t_year VALUES (1, 2024, 2023);` → PANIC `unexpect type YEAR for function vector.GetUnionFunction`
- `INSERT INTO t_decimal VALUES (1, 12345...1234567890);` → PANIC `unexpect type DECIMAL256 for function vector.GetUnionFunction`
- `INSERT INTO t_set VALUES (1, 'read,write', 'red');` → `ERROR 20203: invalid argument cast to uint64`

### Scope of this PR

**Panic / cast-error fixes only.** No new SET DML semantics, no new SET SELECT formatting. The original matrixorigin#24184 reproducers stop crashing; they do not necessarily produce MySQL-equivalent output for SET (that requires the `cast_set_value_to_index` / `cast_set_index_to_value` runtime functions that exist on `main` but not on `3.0-dev` — tracked as a follow-up).

### Fix

- `pkg/container/vector/vector.go`: add T_year / T_decimal256 arms to every per-type switch that previously panicked (`GetAny`, `Shrink`, `ShrinkByMask`, `Shuffle`, `GetUnionAllFunction`, `GetConstSetFunction`, `String`, `RowToString`, `AppendAny`, `GetMinMaxValue`, `InplaceSortAndCompact`, `InplaceSort`). Also include T_geometry in the varlena-group switches so the existing geometry DDL/SHOW support actually matches an executor branch.
- `pkg/container/types`: widen `DecimalWithFormat` to include `Decimal256`; add `EncodeMoYear` / `DecodeMoYear` and `EncodeDecimal256` / `DecodeDecimal256`.
- `pkg/sql/plan/function`: add `operatorUnaryMinusDecimal256` (overload 8) so negative DECIMAL(65,*) literals bind.
- `pkg/frontend/mysql_cmd_executor.go`: map T_year → `MYSQL_TYPE_YEAR`, T_decimal256 → `MYSQL_TYPE_DECIMAL`, T_geometry → `MYSQL_TYPE_GEOMETRY`.
- `pkg/frontend/output.go`: extend `extractRowFromVector` / `extractRowFromVector2` and `ColumnSlices.{convertVectorToSlice, GetInt64, GetUint64, GetDecimal}`; add `arrMoYear` / `arrDecimal256` slices.
- `pkg/vm/engine/tae/compute/compare.go`: add T_year arm to `Compare` / `CompareGeneric` so TAE can order YEAR values during flush.
- `pkg/vm/engine/tae/index/zm.go`: add T_year decoder + range-search branches; skip ZM maintenance for T_decimal256 in `UpdateZM` / `BatchUpdateZM` (matches main — the fixed ZM buffer is 32B while Decimal256 is 64B).

### What this PR explicitly does NOT do

- **SET INSERT/UPDATE via expressions or subqueries.** 3.0-dev's `funcCastForSetType` is literal-only. The earlier version of this PR added a bind-time dispatch for SET columns, but it only worked for literal VALUES; `INSERT ... SELECT`, `UPDATE s = concat(...)`, `VALUES (concat(...))` all still fall through to `cast(varchar -> uint64)`. That dispatch has been reverted to avoid shipping a half-fix.
- **SET SELECT returning member names.** Requires the runtime `cast_set_index_to_value` function (exists on main, not on 3.0-dev) and the `base_binder` column-ref auto-wrap that uses it.
- **DECIMAL256 scale-aware comparison.** `types.CompareDecimal256` ignores scale; this is the case on `main` too — it is not a 3.0-dev regression and warrants a standalone feature PR.
- **DECIMAL256 zonemap.** Skipped the same way main skips it (fixed ZM layout cannot hold the 64B payload). A larger ZM layout is outside this PR.
- **YEAR `GetLength` protocol metadata.** `pkg/defines/type.go:GetLength` has no `MYSQL_TYPE_YEAR` case and falls back to `math.MaxUint32`. Same on main — pre-existing bug, tracked separately.
- **GEOMETRY subtype validation in DML.** 3.0-dev has no `funcCastForGeometryType`; INSERT stores WKT as varchar without subtype checks. Unchanged by this PR.

Approved by: @heni02, @aunjgr, @XuPeng-SH
…ry DAG depth (matrixorigin#24377)

### TL;DR

`data branch diff` and `data branch merge` previously dropped rows
silently whenever the LCA → endpoint chain in the branch DAG had any
intermediate node that performed inserts/updates/deletes before the
endpoint was forked. Symptom: rows that the endpoint inherits via
multi-level cloning were never compared on its side of the diff, so
downstream merges failed to migrate them too. The fix replaces the
historical case-by-case logic with a single ancestor-walking model
that works uniformly for any DAG depth and shape.

### The bug

Concretely, with a chain `t0 → t1 → t2` where t1 inserts `(4, 40)`
before t2 is branched:

```sql
create table t0 (a int primary key, b int);
insert into t0 values (1,10), (2,20), (3,30);

data branch create table t1 from t0;
insert into t1 values (4, 40);
data branch create table t2 from t1;
insert into t2 values (7, 70);

data branch diff t2 against t0;
```

Expected (state-diff):
```
t2 INSERT 4 40
t2 INSERT 7 70
```

Before this PR:
```
t2 INSERT 7 70                ← (4,40) is silently dropped
```

Root cause: `decideCollectRange` only walked the two endpoint
relations. Mutations performed on intermediate ancestors (here, t1's
`insert (4,40)`) live in those intermediates' change streams, not in
either endpoint's. The previous case 2 / case 3 / case 4 sub-branches
each handled at most one extra LCA relation, never the full chain.

### The fix — unified DAG-walk model

For each endpoint X we know the path `[LCA, …, X]` from the DAG. The
new mutations distinguishing the two endpoints live entirely on
`path[LCA, endpoint]` of each side; everything strictly above LCA is
shared and reconciles to no diff. For each ancestor A on that path:

```
windowFrom_A = A.CTS + 1                          (A's own writes)
windowEnd_A  = nextChildOnPath.CloneTS            (A is intermediate)
| endpointSP                         (A is the endpoint)
```

Plus one prune at the LCA: clamp `windowFrom_LCA` up to
`otherFork.Next()` so the prefix shared with the other side via clone
is skipped (would otherwise reconcile to nothing).

The single `buildSideCollectRange` helper applies this to either
side. The historical `case 2 / case 3 / case 4` branching is gone.

### Implementation

* `DataBranchDAG.PathFromAncestor` (new): top-down chain from LCA to
any descendant.
* `branchMetaInfo` (refactored): now carries
`pathFromLCAToTar / pathFromLCAToBase` as the single source of
truth. `lcaType / lcaLeft / lcaRight / lcaOther / tarBranchTS /
baseBranchTS` are gone — their information is derived on demand
via `hasLCA() / tarLCASnapshot() / baseLCASnapshot() /
lcaProbeSnapshot()`.
* `decideCollectRange` (rewritten): three branches kept (case 0
same-table, case 1 unrelated tables, case 2 unified
has-LCA chain walk) — the entire pre-existing case 2/3/4 logic
collapses into one loop driven by the path.
* Dead `lcaType int` parameters removed from `diffDataHelper`,
`hashDiffIfNoLCA`, and `buildHashmapForTable` (they were forwarded
through three layers and never read).

The running example used throughout the new comments is a 19-node
multi-fork tree of depth 4 with 10 leaves (`t0` root, fork to t1/t2/t3,
each forks again twice, leaves t9..t18). Every diff/merge example in
the doc traces against this tree so reviewers can sanity-check the
window arithmetic against a concrete shape.

### BVT additions

* `git4data/branch/diff/diff_12.sql` — 12 cases covering linear chains
with IUD on every chain level, mid-chain post-branch writes,
snapshot mixes, no-PK chains, double-INSERT-same-PK reconciliation,
alternating multi-round IUD, and 1000-row scale.
* `git4data/branch/diff/diff_13.sql` — one giant tree case (19 nodes,
depth 4, 10 leaves) with 14 diff pairs spanning leaf↔root,
cross-subtree, sibling, cousin, intermediate↔intermediate variants.
* `git4data/branch/merge/merge_8.sql` — 9 cases for chain merge:
cascade up the chain, direct grandchild → grandparent merge,
conflict skip/accept across chain depths, snapshot-scoped, no-PK,
alternating-round merges, order-of-merges regression.

### Verification

* Whole `test/distributed/cases/git4data/branch/diff/` BVT —
**1317/1317 PASS, 100%**.
* Whole `test/distributed/cases/git4data/branch/merge/` BVT —
**466/466 PASS, 100%**.
* `pkg/frontend` unit tests pass.

Approved by: @XuPeng-SH, @heni02
旧代码只传 `window.Types[i]` 一个类型,导致 `GROUP_CONCAT(a, b, c ORDER BY k)` 运行时 `vectors` 有多个,但 `argTypes` 只有一个,最终在 `groupConcatExec.Fill` 中越界。

核心修复 `pkg/sql/colexec/window/window.go`:创建 window aggregate executor 时,不要只传 `window.Types[i]` 一个类型,而要传当前聚合全部参数的类型。


`compile/operator.go::constructWindow` 暂时不建议改 separator 逻辑。当前 parser 对 `GROUP_CONCAT` 会始终把 separator 作为最后一个 `FuncExpr.Exprs` 追加进去,默认 separator 也是 `","`,所以 constructWindow 剥掉最后一个参数作为 separator 在此版本中是合理的。

pr解决:
1. 解决 `GROUP_CONCAT` 多个表达式参数的 panic:

```sql
SELECT g, GROUP_CONCAT(a, ':', b ORDER BY k) FROM gc_24359 GROUP BY g;
```

2. 解决多个 `GROUP_CONCAT` 同时使用不同 ORDER BY 的语义问题:

```sql
SELECT
g,
GROUP_CONCAT(a ORDER BY x),
GROUP_CONCAT(b ORDER BY y)
FROM gc_order_bug
GROUP BY g;
```

Approved by: @heni02, @ouyuanning, @aunjgr, @XuPeng-SH
1、修复多角色合并时改写规则不起效的问题
2、多角色起效时,不同角色对同一个库表都有改写规则的时候,如果列一致的情况下,那么做union distinct合并。否则保留最后一个规则

Approved by: @XuPeng-SH, @heni02, @aunjgr
)

- Add BVT test cases for `WEEK(date, mode)` function (93 cases) to verify fix for matrixorigin#24236
- Add BVT test cases for `YEARWEEK(date[, mode])` function (91 cases) to verify fix for matrixorigin#24234
- Add BVT test cases for INTERVAL arithmetic expressions (58 cases) to verify fix for matrixorigin#24235

Approved by: @heni02, @XuPeng-SH
daviszhen and others added 2 commits May 19, 2026 09:21
将lead/lag的default 参数的数据类型cast 到第一个参数的数据类型.

Approved by: @heni02, @aunjgr, @XuPeng-SH
Long scans already skip memory cache writes after exceeding the read block threshold. Also skip full-file preloads so these range reads do not populate disk cache and OS page cache with whole objects.

Co-authored-by: Copilot <[email protected]>
@LeftHandCold
LeftHandCold requested a review from aptend as a code owner May 20, 2026 03:45
Copilot AI review requested due to automatic review settings May 20, 2026 03:45

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot wasn't able to review this pull request because it exceeds the maximum number of files (300). Try reducing the number of changed files and requesting a review from Copilot again.

@LeftHandCold

Copy link
Copy Markdown
Owner Author

Closing duplicate fork-only PR. Official upstream PRs are matrixorigin#24483 and matrixorigin#24484.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.