Skip to content

Commit 0d1ae9e

Browse files
morningmanzhangstar333Gabriel39wangzhaobo957-cloudJay-ju
authored
[feature](be) Read Lance datasets with FileScannerV2 (#69581)
### What problem does this PR solve? Issue Number: None Related PR: #65730 #66608 #66805 #66841 #66999 #67005 #67011 #67110 #67268 #67289 #67325 #67650 #67921 #68028 #68335 #68375 #68615 #68690 #68813 #68815 #68707 #68649 Problem Summary: **In short.** This ports the Lance BE read path of branch-4.1 / branch-4.2 to master, in its branch-4.2 form as of `cabcf45c1af`, plus the BE side of three 4.x changes merged after that snapshot: the search filter `prefilter` flag and profile layout (#68813), distance bounds for `vector_search` (#68815), and the split-level index rule of #68707 that #68815 relies on. It gathers the BE parts of the PRs listed above. Master links `liblance_c` but has no Lance reader, so every `FORMAT_LANCE` scan fails today. With this PR the BE reads Lance datasets through FileScannerV2: plain scans, vector search and full-text search, predicate and runtime-filter pushdown, the schema fetch of a local Lance TVF, and the second phase of TopN lazy materialization. The PR is BE only. The FE connector plugin and the regression suites come in separate PRs, so until then nothing on master plans a Lance scan, and the BE unit tests carry the proof. Original authors: @zhangstar333 @Gabriel39 @wangzhaobo957-cloud @Jay-ju @FANNG1 **Background.** Lance shipped in 4.1.4: the Lance catalog, `local()` / `s3()` with `format=lance`, and the `vector_search` / `full_text_search` TVFs. On master the FE side is being rebuilt as a connector plugin (`fe-connector-lance`), and the BE needs the reader from 4.x. The thrift ids are the branch-4.1 / 4.2 ones, including `TExternalSearchRequest.5` (`prefilter`) and `TVectorSearchParams.6/7` (distance bounds) added after the snapshot, so a BE built from master also reads the Lance scan ranges and search requests that a 4.x FE sends during a rolling upgrade. The one exception is `TVectorSearchOptions` 6, branch-4.2's `approx_mode` (#69852, merged into branch-4.2 after the snapshot and not ported): it is reserved in a comment, and a master BE ignores it, so during a rolling upgrade a 4.2 FE that asks for `fast` or `accurate` gets Lance's default (`normal`). **The problem, and what it cost.** | | master today | with this PR | |---|---|---| | A `FORMAT_LANCE` scan | FileScannerV2 has no Lance reader, so the scan fails with "FileScannerV2 does not support file format" | read by `LanceTableReader` in FileScannerV2 | | `fetch_table_schema` for a local Lance TVF | not handled | returns the Arrow schema mapped to Doris types; Null leaves keep `NULL_TYPE` | | The row location of a Lance row in TopN lazy materialization | `GlobalRowLoacationV2` only has a 32-bit row id, but a Lance row id is a 64-bit id within the snapshot | a version 1 layout carries the 64-bit row id; phase two reads the rows with the dataset's `take_rows` | **How this PR fixes it.** - Reader: `be/src/format_v2/lance/*` and `be/src/format_v2/table/lance_reader.*`, as on branch-4.2 except one local renamed for master's `-Wshadow`. The unit tests construct `RuntimeState(TQueryOptions(), globals)`, because master removed the globals-only constructor. - FileScannerV2: the reader dispatch and `_to_file_format` handle `FORMAT_LANCE` / `"lance"`; `FileFormat::LANCE` is added to its two exhaustive switches. Since #69723 every file scan uses FileScannerV2, so nothing else routes Lance scans (on branch-4.2 a Lance query fails with NotSupported when `enable_file_scanner_v2` is off). - Row locations: `ROW_VERSION {FILE_LOCAL_ROW_ID = 0, LANCE_DATASET_ROW_ID = 1}` and a union layout for `GlobalRowLoacationV2`. Version 0 keeps its byte layout, which static asserts pin. `PRequestBlockDesc.row_id` becomes `uint64` (a proto2 varint, so the wire format is compatible). The materialization operator decodes row locations by version, rejects an unknown version or a wrong size, and stamps `row_location_version`. `RowIdStorageReader` validates the counts and the version, range-checks internal row ids against `uint32`, and groups Lance rows by plan node, snapshot version and dataset URI, so each dataset is read with one `take_rows`. Master's segment batching, scan-slot dedup and fetch concurrency stay as they are. - Thrift (`PlanNodes.thrift`): the external search request body (`TVectorElementType`, `TVectorMetric`, `TSearchVector`, `TVectorSearchParams` 1-7, `TFtsCoverageMode`, `TFtsQueryType`, `TFtsMatchOperator`, `TFullTextSearchParams`, `TSearchFilterFormat`, `TSearchFilter`, `TVectorSearchOptions`, `TExternalSearchQuery`), `TExternalSearchRequest` 2-5 and `TLanceFileDesc` 4-6, all with the branch-4.1 / 4.2 ids. The enums spell out their 4.x values. No id is reused. On master, #70075 reserved `TExternalSearchRequest` 2-5 in comments and added 6 (`paimon_options`); this PR replaces those comments with the fields and leaves 6 as it is. `TVectorSearchOptions` 6 is reserved in a comment for branch-4.2's `approx_mode` (#69852). - After the snapshot (one commit each): - #68813: `prefilter` decides whether the TVF search filter runs before (true) or after (unset / false) candidate selection, for vector and full-text search. The profile groups the Lance counters under `LanceTiming`, `LanceIO`, `LanceIndex`, `LanceVectorIndex`, `LanceScalarIndex`, `LanceExecutionPlan`, `LanceScan`, `LanceSearchPlan` and `LanceDataCache`, uses the 4.x counter names, and registers every scan metric before the statistics callback is installed, so the callback, which Lance invokes from its execution streams, never adds counters. #68813's FE tweak that hides `TUnit.NONE` labels in `AggCounter` belongs to the FE port. - #68707 (part): a vector split searches exactly the index segments FE planned for it, and a split without segments is searched flat whatever `use_index` says; a split with segments under `use_index = false` is rejected. 4.x FEs plan segments only when `use_index` allows them. - #68815: `distance_lower_bound` (inclusive) and `distance_upper_bound` (exclusive) are validated (finite FLOAT values, lower < upper at FLOAT precision, single-vector only) and installed with `lance_scanner_set_distance_range()`, which master's pinned lance-c provides. - Review fixes: - A nested array goes to the Doris SerDes without a copy only when it and every descendant start at offset 0 and reference exactly their child ranges. Lance's legacy (v1) decoder can return a struct or list that is tight at its own level over a Boolean child with a bit offset (a batch that starts mid-byte in the bitmap), and the SerDes reject that under Arrow input validation. - A zero-field `STRUCT<>`, which Lance decodes, is reported as an unsupported column at any nesting level, like the other unsupported Lance types. It used to be typed as a STRUCT that `ColumnStruct` cannot hold (its row count comes from its first child). - A Lance Decimal256 field with precision <= 38 is narrowed to Decimal128 by a safe Arrow cast before decoding. Doris types it DECIMAL32/64/128I by precision, and those SerDes read only Decimal128 arrays; the BE used to crash on the first value, also for nested leaves. Only values a reader can see are cast: before a nested leaf is narrowed, every child slot that no visible row references (under a NULL list, fixed-size-list, map or struct row, or outside a sliced parent) is marked NULL, so a hidden value does not fail the cast and a visible value outside the declared precision still does; map keys, which cannot be NULL, stay checked. - FLOAT / DOUBLE `>=` runtime filters stay residual-only. Lance compares floats by totalOrder, so a pushed `x >= c` dropped negative-NaN rows that Doris keeps. - Runtime filters that mention INT64_MIN stay residual-only. The pinned Lance SQL parser reads `-9223372036854775808` as the negation of a magnitude that it parses as i64 first; the overflow turns the literal into a Float64, which the planner cannot coerce to Int64 or Decimal, so a pushed IN, `>=` or `<=` filter on an INT64 or scale-zero decimal column failed planning and the query failed. Every other i64 is still pushed. - The shared Arrow DATE32 decoding (`DataTypeDateV2SerDe::read_column_from_arrow`) rejects days outside 0000-01-01..9999-12-31 instead of returning a non-null `0000-00-00`, skips null slots and adds the epoch in 64 bits: the DATE32 range part of branch-4.1 / 4.2 #68649. It also changes ADBC, Arrow stream load and paimon-rust reads. - Child values hidden by a NULL list, fixed-size-list, map or struct row are not decoded: the array, map and struct SerDes give the element SerDe a validity bitmap that also clears those slots (`mask_arrow_children_hidden_by_null_parents()`). Arrow leaves them unspecified, and Lance's v2.1 miniblock encoding keeps them, so a hidden 10000-01-01 under a NULL fixed-size list used to fail the DATE32 range check above. Visible values are unchanged; this applies to ADBC, Arrow stream load and paimon-rust as well. The masks come from ExecEnv's tracked Arrow pool. A nested Lance array that is compacted before decoding is masked the same way, at every level, before its `ValidateFull()`, so a hidden invalid UTF-8 string, out-of-precision decimal, Date64 or time no longer fails the batch while a visible one still does. Since #69697 the same masks keep hidden DATETIMEV2 / TIMESTAMPTZ values out of its range checks. A mask costs at most one pass per batch: a NULL row that owns no child slots, or only NULL ones, allocates nothing, and Arrow stream load masks each retained IPC batch once (`mask_arrow_descendants_not_visible()`) before it hands row ranges to the SerDes, so its per-block reads allocate nothing. The one per-block mask left is for map keys under a NULL map row that still owns entries, since a MapArray cannot hold NULL keys; Arrow's map builder writes NULL map rows without entries. - Core: `to_protobuf` keeps `NULL_TYPE` for a NULL literal type, so a Null leaf in ARRAY / MAP / STRUCT no longer comes back as BOOLEAN. The nullable serde reads an Arrow Null array as NULLs without touching buffers that the array does not have. - Configs, caches and metrics, with the 4.x names and defaults: | Config | Default | |---|---| | `lance_index_cache_size_bytes` | 10 GiB | | `lance_metadata_cache_size_bytes` | 1 GiB | | `enable_lance_data_cache` | true | | `lance_data_cache_path` | `${DORIS_HOME}/lance_data_cache` | | `lance_data_cache_disk_capacity_bytes` | 100 GiB | | `lance_data_cache_read_block_size_bytes` | 1 MiB | | `lance_io_buffer_size_bytes` (mutable) | 2 GiB | | `lance_batch_readahead` (mutable) | 5 | | `lance_fragment_readahead` (mutable) | 5 | The BE-wide Lance session (index cache, metadata cache and the optional Foyer disk cache) is created by the first Lance scan, so a BE that never reads Lance creates no cache directory. The first six configs take effect after a restart. A negative cache size (and, while the data cache is enabled, a negative disk capacity or read block size) fails the first Lance scan with a message that names the setting, as does any data-cache value lance-c rejects; the rest of the BE keeps serving. Ten `lance_session_*` metrics report the two in-memory caches. With the defaults, the disk tier keeps 51,200 sparse 2 MiB block files open from the first Lance scan on (100 GiB in blocks of twice the read block size), the same as on branch-4.1 / 4.2. Size `lance_data_cache_disk_capacity_bytes` and `lance_data_cache_read_block_size_bytes` against the BE's open-file limit, or set `enable_lance_data_cache = false`. The index and metadata caches live in lance-c memory: they are not charged to a MemTracker or registered with CacheManager, so memory GC, the cache capacity adjustment under memory pressure and `/api/clear_cache/all` do not shrink them, and `enable_lance_data_cache = false` does not turn them off. lance-c has no call to clear, evict or resize them, so size them with the two configs. The disk tier keys blocks by Lance's store prefix (`scheme$bucket` for S3, GCS and OSS, without the endpoint) and the object path (`thirdparty/patches/lance-c-foyer.patch`). Several endpoints that serve the same bucket name and data-file path with different bytes (data files registered under chosen names or replaced in place; Lance's writers use random file names) share entries, also across a BE restart; such a deployment should set `enable_lance_data_cache = false`. Both are as on branch-4.1 / 4.2 and tracked as follow-ups. A Lance scan's native working set, that is the I/O buffered up to `lance_io_buffer_size_bytes` per scanner, the decode readahead and the operators of a search plan such as the top-k of a flat vector search, is allocated inside lance-c and is charged to neither the query nor its workload group. It counts toward the BE process memory only, so memory GC, which ranks queries by tracked memory, does not attribute it to the Lance query. lance-c accepts no memory budget, so on BEs with little memory headroom size `lance_io_buffer_size_bytes`, `lance_batch_readahead` and `lance_fragment_readahead` for the number of concurrent Lance scanners. As on branch-4.1 / 4.2; tracked as a follow-up. - Build: macOS links `-framework IOKit`. This is the first time objects of `liblance_c.a` are pulled into `doris_be`, so the binary and the link time grow. With this PR `util/rle_encoding.h` reaches 231 TUs and `util/threadpool.h` 589, the same as master `315c2e00331` alone (limits 275 and 660 since #69717), and `gen_cpp/internal_service.pb.h` 562 (master alone 559, limit 660); the reach budgets are unchanged. Not included: the Lance index metadata scanner (`LANCE_INDEX_ENTRIES`); the FE side, including the rolling-upgrade guard that keeps Lance lazy materialization off while an old BE could decode a version 1 row location as version 0; the regression suites; the rest of #68707 (searching historical versions, tags and branches, rejecting fragment ids missing from the snapshot, naming the snapshot in errors and the profile). The `InitReaderAvgTime` / `GetBlockAvgTime` profile fix that #67005 carried goes in a separate PR. **Results.** | | master | with this PR | |---|---|---| | A `FORMAT_LANCE` query | fails before reading anything | read by `LanceTableReader` in FileScannerV2 | | A Lance row in the second phase of TopN lazy materialization | cannot be represented | a version 1 row location, read back with `take_rows` | | A row location of an unknown version or size in phase two | decoded as version 0 | rejected with an error | | An Arrow DATE32 day outside 0000-01-01..9999-12-31 (ADBC, Arrow stream load, paimon-rust, Lance) | read as a non-null `0000-00-00` | the read fails with `InvalidArgument` | BE unit tests (ASAN, macOS arm64, against master's pinned lance-c), on the head rebased onto master `378404eeb12`: 1029 cases in 54 suites run, 1027 pass and 2 Parquet microbenchmarks skip by design. They cover the Lance suites (107: `LanceTableReader*` 83, `LanceNestedNullTest` 10, `LanceRuntimeFilterHelperTest` 10, `LanceSessionManagerTest` 4); the row-location protocol (`MaterializationSharedStateTest`, `RowIdStorageReaderTest`, and the new `RowIdFetchRequestValidationTest`: count mismatch, unknown version, a Lance version on an internal mapping, an internal row id of 2^32); `FileScannerV2Test` (28); the ORC and Parquet reader suites (`NewOrcReaderTest`, `NewParquetReaderTest`, `ParquetScanTest` and the other `Parquet*` suites), whose row ids now go through `file_local`; and the Arrow / protobuf / DATE serde suites with the new `ArrowParentNullsTest`, plus the Iceberg and Parquet reader suites that decode Arrow dates. Reverting any of the review fixes, the #68813 flag, the #68707 split rule or the #68815 bounds makes its new tests fail. The sixth review round adds 13 cases (`ArrowParentNullsTest` 10, `LanceTableReaderTypeTest` 3) and extends one; with them the Arrow SerDe, Lance, ADBC and `IcebergV2ReaderTest` suites run 317 cases: 310 pass and the 7 ADBC SQLite cases skip without a local SQLite driver. The ninth review round adds `LanceRuntimeFilterHelperTest.KeepsInt64MinFiltersResidualOnly` and `LanceTableReaderFilterTest.KeepsInt64MinRuntimeFiltersOutOfLanceScanner`: both pass with the 106 Lance cases (`Lance*`) on the branch rebased onto `339e087b11f`, and restoring `parse_int64()` in either check makes exactly these two fail. On the head rebased onto master `315c2e00331`, with the per-block mask fix (`42cf4e3e5d1`), 328 cases in 24 suites pass: the Arrow SerDe and validation suites, `ArrowParentNullsTest` (15), `LoadArrowPipeTest` (47), the DATETIMEV2 / TIMESTAMPTZ SerDe suites, `ArrowColumnToDorisColumnTest`, `ArrowBlockConvertorTest`, `AdbcReaderTest`, `RemoteDorisV2ReaderTest`, `PaimonRustTableReaderTest` and the Lance suites. Allocating at the first NULL row of each call again fails the new `ArrowParentNullsTest` case and the four new `LoadArrowPipeTest` block cases, dropping the per-batch mask fails the LIST and STRUCT block cases, and returning the child unmasked fails the new timestamp case, four `ArrowParentNullsTest` cases and `LanceTableReaderTypeTest.IgnoresDate32PayloadHiddenByNullParents`. ### Release note Add nine `lance_*` BE configs and `lance_session_*` BE metrics. They take effect once the FE can plan Lance scans. Reading an Arrow DATE32 value outside 0000-01-01..9999-12-31 through ADBC, Arrow stream load or paimon-rust now fails instead of returning 0000-00-00. ### Check List (For Author) - Test <!-- At least one of them must be included. --> - [ ] Regression test - [x] Unit Test - `run-be-ut.sh --run --filter=...` with the suites listed under Results: 420 of 420 pass on macOS arm64 (ASAN) on the content before the rebases, and the Lance and Arrow SerDe suites pass again with the nested-offset, zero-field struct, hidden-child, hidden-Decimal256 and compaction-mask fixes (the ADBC SQLite cases skip without a local SQLite driver). Rebased onto master `43f9ceb48d7`: #69668 conflicted in the scanner selection and in `fetch_table_schema`, which now hands every file format to `format::fetch_file_schema()`, so the Lance branch runs ahead of that call; #69646 added a TopN row-group test that reads the version 0 row location fields, which now go through `file_local` (the earlier rebase onto `5caaeb3e3d4` resolved #69614 and #69601 in the scanner selection, the `FileFormat` enum, its test and the reach budget table). The 95 TUs that this PR changes or that master changed since `5caaeb3e3d4` were syntax-checked against the rebased tree with the UT build flags, and CI runs the suites again. Rebased again onto master `8d88f1cc6f7`: the only conflict was the budget table, where #65858 moved the `util/rle_encoding.h` baseline to 828, and the 163 TUs that this PR changes or that master changed since `43f9ceb48d7` pass the same syntax check. Rebased again onto master `339e087b11f`: the only conflict was the budget table again, where #67292 moved the `util/rle_encoding.h` baseline to 834; #69872 added Arrow type checks ahead of the NULL-parent masking in the map and struct readers and merged cleanly. Of the 114 sources that this PR changes or that master changed since `8d88f1cc6f7`, 111 pass the same syntax check. The other three are master's: two new #67292 files under `storage/segment` fail the same way on master alone, since they compile only inside their unity batch, and this PR adds no source to that target; the #69818 benchmark is not in the UT build and includes only `util/simd` headers that this PR does not touch. Reverting any of the review fixes, the #68813 flag, the #68707 split rule or the #68815 bounds makes its new tests fail. Rebased again onto master `378404eeb12`, which removed the legacy file scanner (#69723): the conflicts were in the scanner-selection code and tests that #69723 deleted, so this PR's Lance lines there went with them (including its `LanceQueriesAlwaysUseScannerV2` test), in the profile keys of `materialization_opertor.cpp`, and in the row fetch of `rowid_fetcher.cpp`, whose non-Lance path is now only `FileScannerV2::read_by_rows`; the deleted V1 ORC / Parquet row id tests took this PR's `file_local` rename with them, and the `util/rle_encoding.h` budget commit is dropped because master is no longer near that limit. Of the 100 sources that this PR changes or that master changed since `339e087b11f`, 99 pass the same syntax check; the other, `format_v2/orc/orc_reader.cpp`, fails the same way on master alone. On the rebased head the suites listed under Results run 1029 cases: 1027 pass and 2 microbenchmarks skip. The test-utility fix that `DataTypeDateTimeV2SerDeTest` needed on macOS (#69695) is now on master. Rebased again onto master `315c2e00331`: the only conflict was `TExternalSearchRequest` in `PlanNodes.thrift`, where #70075 had reserved fields 2-5 in comments; the two commits that add the fields replace those comments, and field 6 stays #70075's `paimon_options`. #69717 cut transitive includes from shared headers: of the 160 sources that this PR changes or that master changed since `378404eeb12`, 156 pass the same syntax check; the two `jemalloc_hook` tests have no compile command on macOS, `runtime/memory/jemalloc_hook.cpp` uses glibc aliases that macOS cannot build (#69819), and `format_v2/table_reader.cpp` alone fails the same way on master alone while its unity batch compiles. The full `doris_be_test` builds and links on the rebased head; `ArrowParentNulls*` and `Lance*` (121 cases) pass before the mask fix, and the 328 cases above with it. - `build-support/check-build-hygiene.sh` (on this branch rebased onto master `315c2e00331`), clang-format 16 and `build-support/run-clang-tidy.sh` on the changed files: all pass; on the changed lines clang-tidy (llvm 22) reports only `readability-inconsistent-ifelse-braces` on the `DORIS_CHECK` lines of the masking functions, the macro's expansion that master's existing `DORIS_CHECK`s report too. - [ ] Manual test (add detailed scripts or steps below) - [ ] No need to test or manual test. Explain why: - Behavior changed: - [ ] No. - [x] Yes. `PRequestBlockDesc.row_id` is `uint64`; phase two of TopN lazy materialization rejects row locations of an unknown version or size; `FORMAT_LANCE` scans run on FileScannerV2; an Arrow DATE32 day outside the Doris DATE range fails the read instead of becoming `0000-00-00`. - Does this need documentation? - [x] No. Lance is documented with the FE connector. - [ ] Yes. <!-- Add document PR link here. eg: apache/doris-website#1214 --> ### Check List (For Reviewer who merge this PR) - [ ] Confirm the release note - [ ] Confirm test cases - [ ] Confirm document - [ ] Add branch pick label <!-- Add branch pick label that this PR should merge into --> --------- Co-authored-by: zhangstar333 <[email protected]> Co-authored-by: Gabriel <[email protected]> Co-authored-by: zhaobo wang <[email protected]> Co-authored-by: jay <[email protected]> Co-authored-by: FANNG <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: zy-kkk <[email protected]>
1 parent 3bacce9 commit 0d1ae9e

185 files changed

Lines changed: 12403 additions & 75 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎be/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -902,6 +902,8 @@ else()
902902
"-framework Foundation"
903903
"-framework SystemConfiguration"
904904
"-framework Security"
905+
# liblance_c.a pulls in the Rust `sysinfo` crate, whose macOS backend calls IOKit.
906+
"-framework IOKit"
905907
)
906908
if (USE_JEMALLOC OR (NOT CMAKE_BUILD_TYPE STREQUAL "DEBUG" AND NOT CMAKE_BUILD_TYPE STREQUAL "RELEASE"))
907909
set(DORIS_LINK_LIBS

‎be/src/common/config.cpp‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1235,6 +1235,26 @@ DEFINE_Validator(variant_max_json_key_length,
12351235
DEFINE_Validator(variant_storage_parse_mode,
12361236
[](const int config) -> bool { return config >= 0 && config <= 2; });
12371237

1238+
// Lance uses one BE-wide session so metadata/index caches and the optional Foyer data-file cache
1239+
// can be shared by all Lance dataset readers.
1240+
DEFINE_Int64(lance_index_cache_size_bytes, "10737418240"); // 10 GiB
1241+
DEFINE_Int64(lance_metadata_cache_size_bytes, "1073741824"); // 1GB
1242+
DEFINE_Bool(enable_lance_data_cache, "true");
1243+
DEFINE_String(lance_data_cache_path, "${DORIS_HOME}/lance_data_cache");
1244+
DEFINE_Int64(lance_data_cache_disk_capacity_bytes, "107374182400"); // 100GB
1245+
DEFINE_Int64(lance_data_cache_read_block_size_bytes, "1048576"); // 1MB
1246+
1247+
// I/O buffering budget per Lance scanner, not a cap on its total memory usage.
1248+
// Runtime changes apply to newly created scanners.
1249+
DEFINE_mInt64(lance_io_buffer_size_bytes, "2147483648"); // 2 GiB
1250+
DEFINE_Validator(lance_io_buffer_size_bytes, [](int64_t value) { return value > 0; });
1251+
1252+
// Read-ahead limits per Lance scanner. Runtime changes apply to newly created scanners.
1253+
DEFINE_mInt32(lance_batch_readahead, "5");
1254+
DEFINE_Validator(lance_batch_readahead, [](int32_t value) { return value > 0; });
1255+
DEFINE_mInt32(lance_fragment_readahead, "5");
1256+
DEFINE_Validator(lance_fragment_readahead, [](int32_t value) { return value > 0; });
1257+
12381258
// block file cache
12391259
DEFINE_Bool(enable_file_cache, "true");
12401260
// ATTENTION: For test only. Keep this enabled in production.

‎be/src/common/config.h‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1300,6 +1300,21 @@ DECLARE_Bool(enable_debug_points);
13001300
DECLARE_Int32(pipeline_executor_size);
13011301
DECLARE_Int32(blocking_pipeline_executor_size);
13021302

1303+
// Lance shared session and optional Foyer data-file cache.
1304+
DECLARE_Int64(lance_index_cache_size_bytes);
1305+
DECLARE_Int64(lance_metadata_cache_size_bytes);
1306+
DECLARE_Bool(enable_lance_data_cache);
1307+
DECLARE_String(lance_data_cache_path);
1308+
DECLARE_Int64(lance_data_cache_disk_capacity_bytes);
1309+
DECLARE_Int64(lance_data_cache_read_block_size_bytes);
1310+
1311+
// I/O buffering budget per Lance scanner, applied when a new scanner is created.
1312+
DECLARE_mInt64(lance_io_buffer_size_bytes);
1313+
1314+
// Read-ahead limits per Lance scanner, applied when a new scanner is created.
1315+
DECLARE_mInt32(lance_batch_readahead);
1316+
DECLARE_mInt32(lance_fragment_readahead);
1317+
13031318
// block file cache
13041319
DECLARE_Bool(enable_file_cache);
13051320
DECLARE_mBool(enable_file_cache_write_from_s3_file_writer);

‎be/src/core/data_type/data_type.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,9 @@ void IDataType::to_protobuf(PTypeDesc* ptype) const {
8484
auto node = ptype->add_types();
8585
node->set_type(TTypeNodeType::SCALAR);
8686
auto scalar_type = node->mutable_scalar_type();
87-
scalar_type->set_type(doris::to_thrift(get_primitive_type()));
87+
// NULL uses UInt8 internally; preserve its logical type even inside complex schemas.
88+
scalar_type->set_type(is_null_literal() ? TPrimitiveType::NULL_TYPE
89+
: doris::to_thrift(get_primitive_type()));
8890
to_protobuf(ptype, node, scalar_type);
8991
}
9092

Lines changed: 322 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,322 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
#include "core/data_type_serde/arrow_parent_nulls.h"
19+
20+
#include <arrow/array/array_base.h>
21+
#include <arrow/array/array_nested.h>
22+
#include <arrow/array/data.h>
23+
#include <arrow/array/util.h>
24+
#include <arrow/buffer.h>
25+
#include <arrow/memory_pool.h>
26+
#include <arrow/type.h>
27+
#include <arrow/util/bit_util.h>
28+
#include <arrow/util/bitmap_ops.h>
29+
30+
#include "common/check.h"
31+
#include "common/logging.h"
32+
#include "runtime/exec_env.h"
33+
#include "util/unaligned.h"
34+
35+
namespace doris {
36+
namespace {
37+
38+
// The pool that LanceRecordBatchConverter::_query_arrow_memory_pool() picks as well: ExecEnv's
39+
// doris::ArrowMemoryPool charges the current query's memory tracker and checks its limit, while
40+
// Arrow's default pool is invisible to both. Only unit tests that never initialize ExecEnv leave
41+
// it null.
42+
arrow::MemoryPool* doris_arrow_memory_pool() {
43+
auto* memory_pool = ExecEnv::GetInstance()->arrow_memory_pool();
44+
return memory_pool != nullptr ? memory_pool : arrow::default_memory_pool();
45+
}
46+
47+
// Offset `row` of a LIST, LARGE_LIST or MAP parent. The offsets buffer may be misaligned (a Python
48+
// UDF hands one over), so it is read like the list and map serdes read it: value_offset() is an
49+
// aligned load of `Offset`, undefined there (UBSAN: load of misaligned address).
50+
template <typename Offset>
51+
int64_t load_offset(const Offset* raw_value_offsets, int64_t row) {
52+
return unaligned_load<Offset>(reinterpret_cast<const uint8_t*>(raw_value_offsets) +
53+
row * sizeof(Offset));
54+
}
55+
56+
// Allocates a validity bitmap of `bit_length` bits from `pool`, with every slot NULL.
57+
Status allocate_null_bitmap(int64_t bit_length, arrow::MemoryPool* pool,
58+
std::shared_ptr<arrow::Buffer>* bitmap) {
59+
auto allocated = arrow::AllocateEmptyBitmap(bit_length, pool);
60+
if (!allocated.ok()) {
61+
return Status::InternalError("allocate Arrow child validity bitmap failed: {}",
62+
allocated.status().message());
63+
}
64+
*bitmap = std::move(allocated).ValueUnsafe();
65+
return Status::OK();
66+
}
67+
68+
// Whether any of the slots [begin, end) of `data` is non-NULL; without a validity buffer every
69+
// slot is. Only such a slot needs hiding, so a NULL row that owns no slots, or only NULL ones,
70+
// costs no bitmap. The slots count from the array offset, the validity bits from the start of
71+
// the buffer.
72+
bool has_valid_slot(const arrow::ArrayData& data, int64_t begin, int64_t end) {
73+
if (begin == end) {
74+
return false;
75+
}
76+
if (data.buffers[0] == nullptr) {
77+
return true;
78+
}
79+
return arrow::internal::CountSetBits(data.buffers[0]->data(), data.offset + begin,
80+
end - begin) != 0;
81+
}
82+
83+
// Copies the validity of the slots [begin, end) of `data` to the same bits of `bitmap`. Validity
84+
// bits are addressed from the start of the buffer, before the array offset.
85+
void copy_validity(const arrow::ArrayData& data, int64_t begin, int64_t end, uint8_t* bitmap) {
86+
if (data.buffers[0] != nullptr) {
87+
arrow::internal::CopyBitmap(data.buffers[0]->data(), data.offset + begin, end - begin,
88+
bitmap, data.offset + begin);
89+
} else {
90+
arrow::bit_util::SetBitsTo(bitmap, data.offset + begin, end - begin, true);
91+
}
92+
}
93+
94+
// Returns a copy of `data` whose validity bitmap is `validity`.
95+
std::shared_ptr<arrow::ArrayData> with_validity(const arrow::ArrayData& data,
96+
std::shared_ptr<arrow::Buffer> validity) {
97+
auto masked = data.Copy();
98+
masked->buffers[0] = std::move(validity);
99+
masked->SetNullCount(arrow::kUnknownNullCount);
100+
return masked;
101+
}
102+
103+
// Keeps the validity of the slots of `target` that a non-NULL row of `parent` references and
104+
// marks every other slot NULL. Row `row` references the slots [slot_begin(row),
105+
// slot_begin(row + 1)) counted from slot `base` of `target`, so the rows of `parent` reference
106+
// [base + slot_begin(0), base + slot_begin(parent.length())). `*masked` is `target` itself when
107+
// every slot to hide is NULL already.
108+
template <typename SlotBegin>
109+
Status mask_unreferenced_slots(const arrow::Array& parent, const SlotBegin& slot_begin,
110+
int64_t base, const std::shared_ptr<arrow::ArrayData>& target,
111+
arrow::MemoryPool* pool, std::shared_ptr<arrow::ArrayData>* masked) {
112+
*masked = target;
113+
// An Arrow Null child has no validity buffer and is NULL in every slot already.
114+
if (target->type->id() == arrow::Type::NA) {
115+
return Status::OK();
116+
}
117+
const int64_t first = base + slot_begin(0);
118+
const int64_t last = base + slot_begin(parent.length());
119+
// Nothing validated the producer's offsets and lengths yet, and a range outside the child
120+
// would be written outside the new bitmap.
121+
if (first < 0 || last < first || last > target->length) {
122+
return Status::InvalidArgument(
123+
"Arrow {} references child slots [{}, {}) of a child with length {}",
124+
parent.type()->ToString(), first, last, target->length);
125+
}
126+
// Only a non-NULL slot needs hiding. A child that an earlier pass masked already, like the
127+
// narrowed Decimal256 leaf that a compaction validates again, therefore costs no bitmap.
128+
std::shared_ptr<arrow::Buffer> validity;
129+
const auto keep_referenced_slots = [&]() -> Status {
130+
RETURN_IF_ERROR(allocate_null_bitmap(target->offset + target->length, pool, &validity));
131+
copy_validity(*target, first, last, validity->mutable_data());
132+
return Status::OK();
133+
};
134+
// A sliced parent leaves the slots of the rows outside the slice unreferenced.
135+
if (has_valid_slot(*target, 0, first) || has_valid_slot(*target, last, target->length)) {
136+
RETURN_IF_ERROR(keep_referenced_slots());
137+
}
138+
for (int64_t row = 0; row < parent.length(); ++row) {
139+
if (!parent.IsNull(row)) {
140+
continue;
141+
}
142+
const int64_t begin = base + slot_begin(row);
143+
const int64_t end = base + slot_begin(row + 1);
144+
if (begin < first || end < begin || end > last) {
145+
return Status::InvalidArgument(
146+
"Arrow {} row {} references child slots [{}, {}) outside [{}, {})",
147+
parent.type()->ToString(), row, begin, end, first, last);
148+
}
149+
// A NULL list or map row may own no slots, and the slots of a NULL row may be NULL
150+
// already. It hides nothing new then, so such NULL rows allocate nothing.
151+
if (!has_valid_slot(*target, begin, end)) {
152+
continue;
153+
}
154+
if (validity == nullptr) {
155+
RETURN_IF_ERROR(keep_referenced_slots());
156+
}
157+
arrow::bit_util::SetBitsTo(validity->mutable_data(), target->offset + begin, end - begin,
158+
false);
159+
}
160+
if (validity != nullptr) {
161+
*masked = with_validity(*target, std::move(validity));
162+
}
163+
return Status::OK();
164+
}
165+
166+
} // namespace
167+
168+
Status mask_arrow_children_hidden_by_null_parents(
169+
const arrow::Array& parent, int64_t start, int64_t end,
170+
const std::shared_ptr<arrow::Array>& child,
171+
const std::function<std::pair<int64_t, int64_t>(int64_t)>& child_slots,
172+
std::shared_ptr<arrow::Array>* masked) {
173+
DORIS_CHECK(child != nullptr);
174+
DORIS_CHECK(masked != nullptr);
175+
*masked = child;
176+
// An Arrow Null child has no validity buffer and is NULL in every slot already.
177+
if (parent.null_count() == 0 || child->type_id() == arrow::Type::NA) {
178+
return Status::OK();
179+
}
180+
const auto& data = *child->data();
181+
std::shared_ptr<arrow::Buffer> validity;
182+
for (int64_t row = start; row < end; ++row) {
183+
if (!parent.IsNull(row)) {
184+
continue;
185+
}
186+
const auto [begin, slot_end] = child_slots(row);
187+
DCHECK(begin >= 0 && begin <= slot_end && slot_end <= data.length);
188+
// A NULL row hides nothing when it owns no slots, as Arrow's list and map builders
189+
// write it, or only NULL ones, as after mask_arrow_descendants_not_visible(). Such a row
190+
// must not allocate: the bitmap covers the whole child, so a caller that reads one large
191+
// batch a few rows at a time would copy the child's validity for every range.
192+
if (!has_valid_slot(data, begin, slot_end)) {
193+
continue;
194+
}
195+
if (validity == nullptr) {
196+
RETURN_IF_ERROR(allocate_null_bitmap(data.offset + data.length,
197+
doris_arrow_memory_pool(), &validity));
198+
copy_validity(data, 0, data.length, validity->mutable_data());
199+
}
200+
arrow::bit_util::SetBitsTo(validity->mutable_data(), data.offset + begin, slot_end - begin,
201+
false);
202+
}
203+
if (validity == nullptr) {
204+
return Status::OK();
205+
}
206+
*masked = arrow::MakeArray(with_validity(data, std::move(validity)));
207+
return Status::OK();
208+
}
209+
210+
Status mask_arrow_child_slots_not_visible(const arrow::Array& parent, int child_index,
211+
arrow::MemoryPool* pool,
212+
std::shared_ptr<arrow::Array>* masked) {
213+
DORIS_CHECK(pool != nullptr);
214+
DORIS_CHECK(masked != nullptr);
215+
DORIS_CHECK(child_index >= 0 && child_index < parent.num_fields());
216+
const auto& child = parent.data()->child_data[child_index];
217+
std::shared_ptr<arrow::ArrayData> masked_child;
218+
switch (parent.type_id()) {
219+
case arrow::Type::LIST: {
220+
const auto* offsets = static_cast<const arrow::ListArray&>(parent).raw_value_offsets();
221+
RETURN_IF_ERROR(mask_unreferenced_slots(
222+
parent, [offsets](int64_t row) { return load_offset(offsets, row); }, 0, child,
223+
pool, &masked_child));
224+
break;
225+
}
226+
case arrow::Type::LARGE_LIST: {
227+
const auto* offsets = static_cast<const arrow::LargeListArray&>(parent).raw_value_offsets();
228+
RETURN_IF_ERROR(mask_unreferenced_slots(
229+
parent, [offsets](int64_t row) { return load_offset(offsets, row); }, 0, child,
230+
pool, &masked_child));
231+
break;
232+
}
233+
case arrow::Type::FIXED_SIZE_LIST: {
234+
const auto& list = static_cast<const arrow::FixedSizeListArray&>(parent);
235+
RETURN_IF_ERROR(mask_unreferenced_slots(
236+
parent, [&list](int64_t row) { return list.value_offset(row); }, 0, child, pool,
237+
&masked_child));
238+
break;
239+
}
240+
case arrow::Type::STRUCT:
241+
RETURN_IF_ERROR(mask_unreferenced_slots(
242+
parent, [offset = parent.offset()](int64_t row) { return offset + row; }, 0, child,
243+
pool, &masked_child));
244+
break;
245+
case arrow::Type::MAP: {
246+
// MapArray::SetData() aborts through ARROW_CHECK_OK(MapArray::ValidateChildData()) once
247+
// the entries struct or the keys may hold a NULL, so the entries that a map row hides
248+
// are marked NULL in the items alone. Entry j of the map is item slot entries.offset + j.
249+
const auto* offsets = static_cast<const arrow::MapArray&>(parent).raw_value_offsets();
250+
const auto& items = child->child_data[1];
251+
std::shared_ptr<arrow::ArrayData> masked_items;
252+
RETURN_IF_ERROR(mask_unreferenced_slots(
253+
parent, [offsets](int64_t row) { return load_offset(offsets, row); }, child->offset,
254+
items, pool, &masked_items));
255+
masked_child = child;
256+
if (masked_items != items) {
257+
masked_child = child->Copy();
258+
masked_child->child_data[1] = std::move(masked_items);
259+
}
260+
break;
261+
}
262+
default:
263+
return Status::InvalidArgument("cannot mask the child slots of Arrow {}",
264+
parent.type()->ToString());
265+
}
266+
*masked = arrow::MakeArray(masked_child);
267+
return Status::OK();
268+
}
269+
270+
Status mask_arrow_descendants_not_visible(const std::shared_ptr<arrow::Array>& array,
271+
arrow::MemoryPool* pool,
272+
std::shared_ptr<arrow::Array>* masked) {
273+
DORIS_CHECK(array != nullptr);
274+
DORIS_CHECK(pool != nullptr);
275+
DORIS_CHECK(masked != nullptr);
276+
*masked = array;
277+
const auto type_id = array->type_id();
278+
// A leaf has no descendants to mask. Other nested layouts, such as list views, unions and
279+
// run-end encoded arrays, are left as they are: the slot mask does not know them, and no
280+
// reader that masks nested arrays maps them to a Doris type.
281+
if (type_id != arrow::Type::LIST && type_id != arrow::Type::LARGE_LIST &&
282+
type_id != arrow::Type::FIXED_SIZE_LIST && type_id != arrow::Type::MAP &&
283+
type_id != arrow::Type::STRUCT) {
284+
return Status::OK();
285+
}
286+
const auto& children = array->data()->child_data;
287+
std::shared_ptr<arrow::ArrayData> masked_data;
288+
for (int child_index = 0; child_index < array->num_fields(); ++child_index) {
289+
std::shared_ptr<arrow::Array> child;
290+
RETURN_IF_ERROR(mask_arrow_child_slots_not_visible(*array, child_index, pool, &child));
291+
std::shared_ptr<arrow::Array> masked_child;
292+
if (type_id == arrow::Type::MAP) {
293+
// The child is the entries struct, whose keys stay unmasked, so only its items are
294+
// masked further down.
295+
const auto& entries = child->data();
296+
std::shared_ptr<arrow::Array> items;
297+
RETURN_IF_ERROR(mask_arrow_descendants_not_visible(
298+
arrow::MakeArray(entries->child_data[1]), pool, &items));
299+
masked_child = child;
300+
if (items->data() != entries->child_data[1]) {
301+
auto masked_entries = entries->Copy();
302+
masked_entries->child_data[1] = items->data();
303+
masked_child = arrow::MakeArray(masked_entries);
304+
}
305+
} else {
306+
RETURN_IF_ERROR(mask_arrow_descendants_not_visible(child, pool, &masked_child));
307+
}
308+
if (masked_child->data() == children[child_index]) {
309+
continue;
310+
}
311+
if (masked_data == nullptr) {
312+
masked_data = array->data()->Copy();
313+
}
314+
masked_data->child_data[child_index] = masked_child->data();
315+
}
316+
if (masked_data != nullptr) {
317+
*masked = arrow::MakeArray(masked_data);
318+
}
319+
return Status::OK();
320+
}
321+
322+
} // namespace doris

0 commit comments

Comments
 (0)